diff --git a/main.go b/main.go index e93fed7..3035cad 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,6 @@ import ( "errors" "flag" "fmt" - "io" "net/http" "os" "os/exec" @@ -103,22 +102,28 @@ func main() { func respondNodePost(w http.ResponseWriter, r *http.Request, nodes *SafeUpdatingSlice) { // TODO: Log errors from this? if r.Method == http.MethodPost { - // TODO: Add actual validation logic here, once we know our data format - // Read (up to 100 chars of) the request body - nodeName, err := io.ReadAll(r.Body) - if err == nil && len(nodeName) > 0 { - // Add our node to the slice, and send a length update to anyone watching - nodes.Lock() - nodes.slice = append(nodes.slice, string(nodeName)) - numNodes := len(nodes.slice) - nodes.Unlock() - log.Debug().Msgf("Buffer updated: %d nodes", numNodes) - nodes.length <- numNodes - fmt.Fprintf(w, "Acknowledged") - } else { + // Validate POSTed data; should be of + // Content-Type: application/x-www-form-urlencoded + err := r.ParseForm() + if err != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, err.Error()) + return + } + nodeName := r.FormValue("data") + if nodeName == "" { w.WriteHeader(http.StatusBadRequest) - fmt.Fprintf(w, "Error reading request body") + fmt.Fprintf(w, "data field must not be empty") + return } + // Add our node to the slice, and send a length update to anyone watching + nodes.Lock() + nodes.slice = append(nodes.slice, nodeName) + numNodes := len(nodes.slice) + nodes.Unlock() + log.Debug().Msgf("Buffer updated: %d nodes", numNodes) + nodes.length <- numNodes + fmt.Fprintf(w, "Acknowledged") } else { w.WriteHeader(http.StatusMethodNotAllowed) fmt.Fprintf(w, "This endpoint must be POSTed to")