Documentation
¶
Overview ¶
Package httpbody provides helpers for reading HTTP response bodies defensively, capping how much memory a response can make the reader buffer.
A typical HTTP client applies the cap in its Do method, so every response it returns is capped unless the request opts out:
res, err := c.Client.Do(req) httpbody.LimitSize(res)
Index ¶
Constants ¶
const DefaultMaxSize = 1 << 20
DefaultMaxSize is the default response body size cap, in bytes, used when a context carries no override set with WithMaxSize. HTTP clients that apply response body caps should honor it, so requests can tune or disable the cap uniformly across clients.
Variables ¶
var ErrTooLarge = errors.New("response body too large")
ErrTooLarge is reported by a body wrapped with LimitSize once more than the configured number of bytes have been read. The error text includes the limit that was exceeded.
Functions ¶
func LimitSize ¶
LimitSize replaces res.Body with a wrapper that fails reads with an error wrapping ErrTooLarge once more than the response body size limit in res.Request's context, per WithMaxSize, has been read: DefaultMaxSize by default, or if res has no Request. A limit of zero or less imposes no limit, removing any limit a previous call set.
Repeated calls to LimitSize or LimitSizeTo replace the previous limit rather than compounding it, so a later call can raise or remove the limit an earlier one set. If bytes have already been read through a previous limit, the new limit counts bytes read after it was applied.
Unlike io.LimitReader, which silently truncates at its limit, the wrapper reports an oversize body so callers can distinguish a short body from a too-large one. A body of at most the limit, including one of exactly the limit, reads back without error.
func LimitSizeTo ¶
LimitSizeTo is like LimitSize but caps res.Body at exactly max bytes, ignoring any override in res.Request's context. A max of zero or less imposes no limit, removing any limit a previous call set. Repeated calls to LimitSize or LimitSizeTo replace the previous limit rather than compounding it.
func MaxSize ¶
MaxSize returns the response body size cap in ctx: the value set with WithMaxSize, or DefaultMaxSize if ctx carries none.
func WithMaxSize ¶
WithMaxSize returns a context that sets the response body size cap to max, instead of DefaultMaxSize, for HTTP clients that apply response body caps. A max of zero or less disables the cap. Disable it for responses that stream an unbounded number of individually bounded messages, like a streaming map response.
Types ¶
This section is empty.