Limit and validate HTTP request bodies
Limit and validate HTTP request bodies
An HTTP body can be missing, malformed or very large. Limit bytes before parsing, validate fields and reject trailing documents. Content-Length alone is not a sufficient bound: the length may be unknown. MaxBytesReader wraps the body and reports a typed MaxBytesError when reads exceed the limit.
package main
import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func readName(w http.ResponseWriter, r *http.Request) (string, int) { r.Body = http.MaxBytesReader(w, r.Body, 64) defer r.Body.Close() d := json.NewDecoder(r.Body) d.DisallowUnknownFields() var v struct { Name string `json:"name"` } e := d.Decode(&v) if e == nil { var extra any e = d.Decode(&extra) if e == io.EOF { if strings.TrimSpace(v.Name) == "" { return "", 400 } return v.Name, 200 } if e == nil { return "", 400 } } var limit *http.MaxBytesError if errors.As(e, &limit) { return "", 413 } return "", 400}func main() { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { name, status := readName(w, r) w.WriteHeader(status) fmt.Fprint(w, name) }) for _, b := range []string{`{"name":"Ada"}`, `{"name":""}`, `{"name":"Ada","extra":1}`, `{"name":"Ada"} {}`} { w := probe(h, "POST", "/names", b) fmt.Printf("%d %q\n", w.Code, w.Body.String()) }}The decoder forbids unknown struct fields. A second Decode must reach EOF: otherwise the request contains another value or invalid suffix. A nonblank name is required. This is a deliberately small schema; DisallowUnknownFields does not reject duplicate JSON keys or case-insensitive field matches. For APIs needing those guarantees, use additional validation. A real server normally owns body closure; the wrapper is explicitly closed in this helper.
Expected output:
200 "Ada"400 ""400 ""400 ""Detect a byte limit violation
package main
import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func readName(w http.ResponseWriter, r *http.Request) (string, int) { r.Body = http.MaxBytesReader(w, r.Body, 64) defer r.Body.Close() d := json.NewDecoder(r.Body) d.DisallowUnknownFields() var v struct { Name string `json:"name"` } e := d.Decode(&v) if e == nil { var extra any e = d.Decode(&extra) if e == io.EOF { if strings.TrimSpace(v.Name) == "" { return "", 400 } return v.Name, 200 } if e == nil { return "", 400 } } var limit *http.MaxBytesError if errors.As(e, &limit) { return "", 413 } return "", 400}func main() { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, status := readName(w, r); w.WriteHeader(status) }) for _, n := range []int{53, 54} { b := `{"name":"` + strings.Repeat("a", n) + `"}` fmt.Println(len(b), probe(h, "POST", "/names", b).Code) }}Exactly 64 bytes are allowed; 65 bytes with this valid JSON structure fail with 413. A malformed body may fail earlier with 400 before the limit is encountered. Choose a limit for the endpoint and read before replying. Validate Content-Type separately when your API requires application/json; also bound decompressed data if compression is supported.
Expected output:
64 20065 413Try it locally
Use readName on whitespace-only name and on valid JSON followed by whitespace; print statuses.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 04: Limit and validate HTTP request bodies
Check the lesson objective before moving on.
What does MaxBytesReader protect?
Why perform a second Decode?