Package reqbody
Overview
Package reqbody opens a request's body for reading: it removes the content codings in Content-Encoding and caps the body's size, both as sent and as decoded.
Capping the decoded size matters as much as the raw size, because a small gzip body can decode to gigabytes. A handler reads the body through Open, and maps ErrTooLarge to 413, ErrUnsupportedEncoding to 415 and ErrInvalidEncoding to 400:
body, err := reqbody.Open(w, r, 1<<20, 8<<20)
if err != nil {
// Only ErrUnsupportedEncoding: the coding isn't one we decode.
}
defer body.Close()
data, err := io.ReadAll(body) // ErrTooLarge or ErrInvalidEncoding.Index
Constants
const AcceptEncoding = "gzip"AcceptEncoding lists the content codings Open decodes, for the Accept-Encoding field of a 415 response. RFC 9110, Section 15.5.16, says a 415 caused by an unsupported content coding ought to send it.
Variables
var (
// ErrTooLarge is returned when reading a body past either cap.
ErrTooLarge = errors.New("request body too large")
// ErrUnsupportedEncoding is returned by Open for a Content-Encoding it
// doesn't decode.
ErrUnsupportedEncoding = errors.New("unsupported content encoding")
// ErrInvalidEncoding is returned when reading a body whose coded form is
// corrupt, such as one that isn't gzip at all.
ErrInvalidEncoding = errors.New("invalid content encoding")
)Functions
Open source
func Open(w http.ResponseWriter, r *http.Request, maxRaw, maxDecoded int64) (io.ReadCloser, error)Open returns r's body with the codings listed in Content-Encoding removed, in reverse order of application (RFC 9110, Section 8.4). It decodes gzip and its alias x-gzip (Section 8.4.1.3), and skips identity.
Reading returns an error wrapping ErrTooLarge once more than maxRaw bytes arrive, or more than maxDecoded bytes decode. Like http.MaxBytesReader, the raw cap also tells the server to close the connection. Open itself returns only ErrUnsupportedEncoding, before reading anything. Close the returned body when done.