Read Exact Byte Counts With io.ReadFull

Frame parsing needs exact lengths: io.ReadFull reads until the buffer is full and reports ErrUnexpectedEOF on short payloads instead of silent truncation.

GoData Integrity

Code

gosnippet
33 lines
package main

import (
	"bytes"
	"fmt"
	"io"
)

func main() {
	// 帧格式:4 字节大端长度头 + 载荷
	frame := []byte{0x00, 0x00, 0x00, 0x05, 'h', 'e', 'l', 'l', 'o'}

	r := bytes.NewReader(frame)

	var header [4]byte
	// ReadFull:读满 len(header) 才返回;少一个字节都算错误
	if _, err := io.ReadFull(r, header[:]); err != nil {
		panic(err)
	}
	fmt.Println("declared payload size:", header[3])

	payload := make([]byte, header[3])
	if _, err := io.ReadFull(r, payload); err != nil {
		panic(err)
	}
	fmt.Println("payload:", string(payload))

	// 载荷不足时:已读 n>0 但没读满 → ErrUnexpectedEOF,而不是静默短读
	truncated := bytes.NewReader([]byte{1, 2, 3})
	buf := make([]byte, 10)
	n, err := io.ReadFull(truncated, buf)
	fmt.Printf("truncated: read %d bytes, err=%v\n", n, err)
}

The logic as it executes

Read Exact Byte Counts With io.ReadFull comes down to the function main.

Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Watch out for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

The demo output is labeled (declared payload size:, payload:, truncated: read); each label names the call that printed it.

Core lines

payload := make([]byte, header[3])
buf := make([]byte, 10)

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 2 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does Read Exact Byte Counts With io.ReadFull print when run?
Execute the whole file; each printed line is prefixed with a label like `declared payload size:`, `payload:`, `truncated: read`.