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 MiBRelated terms
- io.ReadAll — The Go function that reads an io.Reader until the end and returns everything as one slice of bytes.
- untrusted input — Any data a program did not create itself, including arguments, form fields, request bodies, file contents, file names and environment variables.
- io.Reader — The Go interface for anything you can read bytes from, such as a file, a network connection or an HTTP response body.
Taught in
- Streams and the io Package — Concurrent Systems Programming with Go