Go: Distinguish an absent header from a truncated header
A four-byte protocol header can arrive in several reads. io.ReadFull collects exactly that many bytes and distinguishes an empty stream from a stream that ends partway through the header.
Set up
Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as go-readfull-fixed-size-header.go:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
for _, input := range []string{"", "AB", "ABCD", "ABCDE"} {
reader := strings.NewReader(input)
var header [4]byte
n, err := io.ReadFull(reader, header[:])
switch input {
case "":
if n != 0 || err != io.EOF {
panic("empty header")
}
case "AB":
if n != 2 || err != io.ErrUnexpectedEOF {
panic("short header")
}
default:
if n != 4 || err != nil {
panic("complete header")
}
}
fmt.Printf("%q: read=%d error=%v remaining=%d\n", input, n, err, reader.Len())
if err == nil {
fmt.Printf("header=%q\n", header[:])
}
}
}Run:
go run go-readfull-fixed-size-header.goObserved output:
"": read=0 error=EOF remaining=0
"AB": read=2 error=unexpected EOF remaining=0
"ABCD": read=4 error=<nil> remaining=0
header="ABCD"
"ABCDE": read=4 error=<nil> remaining=1
header="ABCD"Read the result
The destination slice sets the required length. EOF before any byte is read produces io.EOF; EOF after some bytes produces io.ErrUnexpectedEOF. A complete header succeeds, and the fifth byte remains available for the next part of the protocol.
Only the success branch interprets the header. On failure, the buffer can contain a partial prefix followed by untouched bytes. Treating that buffer as a complete message would hide truncation.
Apply it carefully
This example uses an in-memory reader, so it cannot block on a peer. Network readers need deadlines or another cancellation strategy. A complete header is only a framing check: validate magic bytes, lengths and other fields separately. The function consumes bytes and does not roll them back on failure. If a reader returns a different error before filling the buffer, that error is returned; do not classify every failure as EOF.
See the Go standard-library reference.
Clean up
Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.
rm -- go-readfull-fixed-size-header.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.