Reading specific number of bytes from a buffered reader in golang

Note that the bufio.Read method calls the underlying io.Read at most once, meaning that it can return n < len(p), without reaching EOF. If you want to read exactly len(p) bytes or fail with an error, you can use io.ReadFull like this:

n, err := io.ReadFull(reader, p)

This works even if the reader is buffered.

Leave a Comment