HTTP Middleware for Request Body Limits
Cap JSON request bodies with MaxBytesReader, reject oversized payloads with 413, and reuse the middleware across handlers.
Code
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
type Middleware func(http.Handler) http.Handler
type Payload struct {
Name string `json:"name"`
}
func LimitBody(maxBytes int64) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
next.ServeHTTP(w, r)
})
}
}
func decodePayload(w http.ResponseWriter, r *http.Request) (Payload, error) {
var payload Payload
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&payload); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
http.Error(w, fmt.Sprintf("body exceeds %d bytes", tooLarge.Limit), http.StatusRequestEntityTooLarge)
return payload, err
}
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return payload, err
}
if strings.TrimSpace(payload.Name) == "" {
http.Error(w, "name is required", http.StatusUnprocessableEntity)
return payload, errors.New("name is required")
}
return payload, nil
}
func main() {
handler := LimitBody(64)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
payload, err := decodePayload(w, r)
if err != nil {
return
}
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "created %s\n", payload.Name)
}))
bodies := []string{
`{"name":"ada"}`,
`{"name":"` + strings.Repeat("x", 80) + `"}`,
}
for _, body := range bodies {
request := httptest.NewRequest(http.MethodPost, "/users", strings.NewReader(body))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
fmt.Printf("status=%d body=%q\n", recorder.Code, strings.TrimSpace(recorder.Body.String()))
}
}
The mechanics of the snippet
Structurally, expect the functions LimitBody, decodePayload and main and nothing else.
Repetition is confined to for _, body := range bodies — the rest of the file is straight-line. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Errors are ordinary return values; skipping the
errcheck means using a zero value silently.
Applying it
Entry signature: func LimitBody(maxBytes int64) Middleware
The demo output is labeled (status=); each label names the call that printed it.
The entry point wires LimitBody and decodePayload together — run it once and the whole demo flows.
Statements that matter
return payload, errors.New("name is required")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
next.ServeHTTP(w, r)
})
if errors.As(err, &tooLarge) {
http.Error(w, fmt.Sprintf("body exceeds %d bytes", tooLarge.Limit), http.StatusRequestEntityTooLarge)
return payload, err
}
Interactive Tools for This Topic
CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.
FAQ
- How do errors reach the caller?
- By return value: each fallible call hands back an `error`, checked at 2 places here.
- What does HTTP Middleware for Request Body Limits print when run?
- The script runs standalone; its 1 labeled outputs include `status=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.