Go HTTP JSON Body Limits: Reject Oversized Requests with MaxBytesReader
Reproduce oversized JSON bodies hidden by LimitReader, then use MaxBytesReader and an EOF check to test size boundaries, unknown length, extra JSON values, and error classification.
When limiting JSON request bodies in a Go HTTP server, distinguish truncating reads with io.LimitReader from rejecting oversized requests. Wrap the body in http.MaxBytesReader and check for EOF after decoding one JSON value to include excessive trailing whitespace in the size check. The example below reproduces the same 65-byte request receiving 200 on the flawed path and 413 on the corrected path.
Conceptual illustration of a server accepting a fitting request and rejecting an oversized one intact; not an actual flow diagram or measurement.
Written and documentation checked: December 6, 2026. Execution environment: Go 1.24.7, Linux/amd64, using standard encoding/json and net/http/httptest. These results are not from the latest Go release or a test of actual HTTP connections.
Stopping reads does not detect excess input
The io.LimitReader contract returns EOF after a specified number of bytes. It does not report an error indicating that more data exists beyond the limit. A complete JSON value in the prefix can therefore appear valid while trailing data is hidden.
The reproduction appends spaces to the 13-byte value {"text":"ok"}. Reading up to 64 bytes still reveals only valid JSON and whitespace. Even when the actual input is 65 bytes, the world exposed by LimitReader ends at byte 64. This is easier to miss than truncating a JSON object midway and receiving a syntax error.
| Mechanism | Role | Size-limit implementation decision |
| io.LimitReader | Produces EOF after a byte count | Useful for truncating reads, but does not establish whether input exceeds the limit |
| http.MaxBytesReader | Reports a read beyond the limit as an error | Classify that error and reject the request |
| Content-Length | Metadata for a known body length | Can assist early rejection but does not replace a limit on actual reads |
The MaxBytesReader documentation describes a request-body limiting API that returns *http.MaxBytesError on reads beyond the limit and closes the underlying reader when closed. The handler below explicitly writes the 413 response. Wrapping the reader alone does not implement the desired error response.
Wrap the body and inspect what follows the JSON
The json.Decoder.Decode documentation defines Decode as reading the next single JSON value. A successful first Decode does not establish the end of the request. Attempt a second Decode using the same decoder, accepting only EOF and rejecting another JSON value or any other error.
Keep the same decoder to inspect data already read into its internal buffer. Do not switch to reading only the remaining original Body. Decoder.More checks for another element inside an array or object; it is not a replacement for checking EOF at the top level of a request.
Save the following as body-limit-demo.go. strict=false is the deliberately flawed comparison path; strict=true is the path to adapt for a service. The example returns 200 after body validation and implements no business operation.
Run:
Observed results: boundaries and error classification
On Go 1.24.7, the program exited with code 0 and printed the following. An unexpected status code causes a panic.
Whitespace is part of the body's byte count. The test accepted exactly 64 bytes and rejected the 65-byte body with excess whitespace. A request with ContentLength=-1 was also classified as 413 through body reads. This verifies handler behavior without depending on length metadata; it does not reproduce chunked transfer over actual TCP.
The large JSON string produced 413, while two JSON values within the limit and incomplete JSON produced 400. Actual limit errors are identified with errors.As. Do not turn every JSON error into 413 or classify errors by their message text.
Conversely, a large malformed body can produce 400 if the parser encounters a syntax error before reading up to the limit. This implementation does not promise that every oversized body will be classified as 413. It sends 413 when it observes a size error and validates through the end before accepting a request as successful.
Byte limits do not replace business validation or time limits
The 64-byte limit makes the boundary easy to reproduce. Choose production limits in body bytes, including JSON syntax, field names, and whitespace. This is separate from TTS text character counts or utterance duration limits. Adapt the function to pass the validated input structure to the business layer, and start side effects such as synthesis or database writes after complete validation, not immediately after the first Decode.
The example does not implement policies for required fields, empty text, null, unknown fields, or duplicate keys. Body-size and single-value checks do not complete API schema validation. Authentication, Content-Type checks, and error response formats also need to follow the actual API contract.
A size limit does not solve a slow client withholding EOF. Design server read time limits and proxy settings separately. With body-decompression middleware, the limiting reader's position determines which bytes it counts. Consider whether both transferred size and decompressed size need independent limits. This example includes no decompression.
This verification invokes the handler directly with an in-memory reader and ResponseRecorder. It does not validate actual connection closure, connection reuse, HTTP/2 behavior, proxies, decompression, or timeouts. Before production use, check boundaries and failure paths with the deployed server and proxy combination.
한국어판:
Go HTTP JSON 본문 크기 제한: LimitReader의 EOF 함정과 MaxBytesReader