Go / Editorial solution guide
Diagnose partial reads and unexpected EOF
Preserve returned bytes and distinguish truncation from ordinary end of input.
Read-only knowledge base · No public comments
Recognize the symptoms
A record is truncated or the last bytes disappear when a read reports an error.
Understand the likely causes
- The caller assumes every read fills its buffer or checks the error before processing returned bytes.
Capture bytes and error
Reproduce with a fixed synthetic stream and record the number of bytes returned together with the error. A read can return data and an error in the same call, and a short read is not automatically a malformed stream. Decide whether the protocol requires an exact-length field or permits a shorter final record before changing the code. Avoid logging private payloads during diagnosis.
Understand the reader contract
The io.Reader contract requires callers to process n bytes before considering a returned error. A reader may return the final bytes with io.EOF or return those bytes with nil and report EOF on the next call. Distinguish ordinary end of input from a truncated fixed-size record. A result of zero bytes and nil does not itself mean EOF and should not be treated as a complete record.
Choose a read strategy
For an exact-length field, io.ReadFull collects bytes until the buffer is filled or an error prevents completion. The example reads two bytes into a four-byte buffer and reports io.ErrUnexpectedEOF with the count. For a streaming parser, process each nonzero read before handling its error instead. Preserve the number of bytes actually obtained and apply the protocol’s explicit truncation policy.
package main
import (
"fmt"
"io"
"strings"
)
func main() {
buf := make([]byte, 4)
n, err := io.ReadFull(strings.NewReader("go"), buf)
fmt.Println(n, err == io.ErrUnexpectedEOF)
}
2 true
ReadFull returns two bytes and identifies an incomplete field.
Verify partial input
Test a complete field, empty input, a truncated field, and a custom reader that returns bytes and an error together. Verify both the consumed bytes and the error classification; a successful test using only an in-memory reader may miss the combined-result case. Repeat the original operation with its real reader after the fix, and check that resources owned by the caller are closed on all exit paths.
Verify the fix
Complete and truncated records follow the documented protocol, and bytes returned with an error are handled.
Keep it from recurring
- Test short reads, data with errors, and empty input using controlled readers.