Skip to content
Tutorials Center
My learning

Topics

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.

Go
data, err := io.ReadAll(resp.Body)

Try it

Go Reading a whole stream

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.

Go Errors and safe limits

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

Go
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. ReadAll keeps everything. For HTTP requests from users, wrap the body with io.LimitReader or http.MaxBytesReader first, as in readLimited above.
  • Prefer streaming for big data. io.Copy, bufio.Scanner or a json.Decoder process the data piece by piece.
  • Files: os.ReadFile(name) opens, reads and closes in one call, so you rarely need ReadAll(file) for a path.
  • Always close the source. ReadAll never closes anything; with HTTP use defer resp.Body.Close(), and read the whole body when you want the connection to be reused.
  • Replaces ioutil.ReadAll. Since Go 1.16 io.ReadAll is the standard function; io/ioutil is 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 with json.Unmarshal.