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.
Code
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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.