body-limits

command
v14.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 3 Imported by: 0

Documentation

Overview

Capping request body size, app-wide and per route.

ContextOptions.BodyMaxMemory limits the bytes read from a body by Body, ReadJSON, ReadJSONStream and ReadMultipartRelated - and therefore by everything built on them, including ReadXML/ReadYAML/ReadBody and ctx.BindJSON. The default 0 means no limit. Reading past the cap fails with context.ErrRequestEntityTooLarge, which rest/errors renders as a structured 413 TOO_LARGE.

The bodylimit middleware applies the same enforcement wherever it is registered. It rejects a request up front when the declared Content-Length already exceeds the limit, and wraps the body reader to catch chunked or compressed bodies that only reveal their size while being read.

PostMaxMemory is a different knob - it bounds multipart form buffering, not body size. See ../uploads.

Learn: cap request bodies for the whole app and tighter per route, and answer a structured 413 from either limit. Before: ../uploads

Run:

go run main.go

Try:

curl -i -X POST http://localhost:8080/notes -H 'Content-Type: application/json' \
  -d '{"text":"hello"}'                                                           # 200, {"chars":5}
printf '{"text":"%s"}' "$(head -c 2000000 /dev/zero | tr '\0' a)" > big.json      # a ~2MB JSON body
curl -i -X POST http://localhost:8080/notes -H 'Content-Type: application/json' \
  --data-binary @big.json                                                         # 413 TOO_LARGE, the 1MB app-wide cap
curl -i -X POST http://localhost:8080/uploads/blob --data-binary @big.json        # 413 TOO_LARGE, the 64KB route limit

Next: ../../05-response/rest-helpers

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL