Go Reference ยท Errors, I/O and Files
Go io.ReadAll() function
Reference for Go io.ReadAll: read a reader to EOF into a byte slice, the EOF-is-not-an-error rule, memory risks with HTTP bodies and safer limits.
io.ReadAll(r) reads from a reader until it hits the end and returns all the bytes in a new slice. It is the quick way to turn a stream into a value: an HTTP response body, a file you already opened, the standard input, or the output of a command.
A normal end of input is not an error, so on success err is nil. Anything read before an error is still returned, together with that error.
data, err := io.ReadAll(resp.Body)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func ReadAll(r Reader) ([]byte, error)
| Name | Description |
|---|---|
r |
The reader to drain. |
Returns: all bytes read, and nil if the reader ended with io.EOF. If another error occurs, the bytes read so far and that error are returned.
Edge cases: an empty reader gives an empty, non-nil slice ([]byte{}, length 0); you can tell nothing was read by checking the length. The slice grows as needed, so very large inputs use a lot of memory and may be copied while growing.
Usage notes
- Memory is unbounded.
ReadAllkeeps everything. For HTTP requests from users, wrap the body withio.LimitReaderorhttp.MaxBytesReaderfirst, as inreadLimitedabove. - Prefer streaming for big data.
io.Copy,bufio.Scanneror ajson.Decoderprocess the data piece by piece. - Files:
os.ReadFile(name)opens, reads and closes in one call, so you rarely needReadAll(file)for a path. - Always close the source.
ReadAllnever closes anything; with HTTP usedefer resp.Body.Close(), and read the whole body when you want the connection to be reused. - Replaces
ioutil.ReadAll. Since Go 1.16io.ReadAllis the standard function;io/ioutilis deprecated. - Newer Go versions are faster: the implementation avoids repeated copying by growing the buffer in larger steps, but the memory use is still proportional to the input.
- Text vs bytes: convert with
string(data)only when the content is text; JSON can be decoded straight from the bytes withjson.Unmarshal.