io.LimitReader

The Go function that wraps an io.Reader so it stops after a set number of bytes, capping how much you will read.

In more detail

Put it in front of io.ReadAll or a decoder when the input comes from outside, such as a response body or an upload. A misbehaving or hostile source then cannot make your program allocate unlimited memory.

Example

reader := io.LimitReader(resp.Body, 1<<20)  // at most 1 MiB

Related terms

Taught in

References