Example: io.ReadFull
io.ReadFull reads from an io.Reader until the buffer is completely filled or an error occurs.
Unlike a standard io.Read, io.ReadFull will not return early with a success status if it reads fewer bytes than requested. It continues reading until one of the following conditions is met:
- Success: The buffer (
len(buf)) is completely filled. - Failure: An error occurs before the buffer is completely filled. If the stream ends early, the returned error is typically
io.ErrUnexpectedEOF.
Common Use Cases
- Binary protocol parsing (e.g., reading fixed-length headers)
-
- Framed protocol parsing (reconstructing fixed-length protocol headers over TCP streams)
- Reading file headers or metadata
- Processing fixed-size messages
Quick Start
The simplest scenario: precisely reading 5 bytes from a data source.
Output:
The Core Value A single call to
reader.Read(buf)does not guarantee thatbufwill be completely filled. It may return after reading only part of the requested data, leaving the caller responsible for repeatedly callingReaduntil enough bytes have been collected.In contrast,
io.ReadFull(reader, buf)establishes a strict API contract: as long as it returnserr == nil, it guarantees that exactly len(buf) bytes have been read.
Parsing Fixed-Length Protocol Headers
In binary protocols, a fixed-size header is typically defined at the very beginning of a message.
For example:
When parsing this protocol, you must fully read the 8-byte header first; otherwise, you cannot determine the length of the trailing payload.
Output:
Edge Case Handling: Error Mechanism on Insufficient Data
io.ReadFull eventually returns an error after exhausting the available data.
Output:
This error indicates that:
- The Reader reached its end.
- However, the requested data length was not fully met.
This is distinct from a standard io.EOF:
TCP is a byte stream rather than a message-oriented protocol. A single Write by the sender does not necessarily correspond to a single Read by the receiver. io.ReadFull is commonly used to reconstruct fixed-length portions of a protocol, such as headers, before parsing the remaining payload.