Return ErrResponseTooLarge instead of truncating response body

WithMaxResponseBody wrapped the body in io.LimitedReader, which returns EOF
at the cap, so Bytes/JSON/XML silently returned a truncated body with a nil
error despite the documented contract. Read one byte past the limit and
return the new ErrResponseTooLarge sentinel when exceeded; bodies exactly at
the limit still succeed.
This commit is contained in:
2026-05-23 13:47:13 +03:00
parent 2d4a06e715
commit e8c4577c6f
5 changed files with 48 additions and 12 deletions

View File

@@ -102,9 +102,12 @@ func (c *Client) Do(ctx context.Context, req *http.Request) (*Response, error) {
}
if c.maxResponseBody > 0 {
// Read one byte past the limit so we can distinguish "exactly at the
// limit" (allowed) from "exceeds the limit" (ErrResponseTooLarge).
resp.Body = &limitedReadCloser{
R: io.LimitedReader{R: resp.Body, N: c.maxResponseBody},
C: resp.Body,
r: io.LimitReader(resp.Body, c.maxResponseBody+1),
c: resp.Body,
limit: c.maxResponseBody,
}
}