Sniff Headers And Frame Records With bufio.Reader

Inspect leading bytes with bufio.Reader.Peek without advancing the cursor, then split records via ReadBytes while handling a trailing io.EOF.

GoData Integrity

Code

snippet
package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"strings"
)

func main() {
	raw := "HDR:v1\nalpha\nbeta\ngamma"
	r := bufio.NewReader(strings.NewReader(raw))

	// Peek inspects the magic prefix without advancing the cursor
	prefix, err := r.Peek(4)
	if err != nil {
		fmt.Println("peek failed:", err)
		return
	}
	fmt.Printf("header sniffed: %q (buffered=%d)\n", prefix, r.Buffered())

	// ReadBytes keeps the delimiter and may return data alongside io.EOF
	for step := 1; ; step++ {
		chunk, err := r.ReadBytes('\n')
		trimmed := bytes.TrimRight(chunk, "\r\n")
		if len(trimmed) > 0 {
			fmt.Printf("record %d: %q (eof=%t)\n", step, trimmed, errors.Is(err, io.EOF))
		}
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			fmt.Println("read error:", err)
			return
		}
	}
}

Inside the implementation — Sniff Headers And Frame Records With bufio.Reader

The snippet is organized around the function main.

A single loop drives the file — for step := 1; ; step++. err is inspected at 2 call sites before any result is trusted.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func main()

The file’s steps show up in the output as peek failed:, header sniffed:, record.

Core lines

if errors.Is(err, io.EOF) {
	break
}
if err != nil {
	fmt.Println("peek failed:", err)
	return
}
if err != nil {
	fmt.Println("read error:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Sniff Headers And Frame Records With bufio.Reader print when run?
Running the file directly is enough — expect labeled output lines such as `peek failed:`, `header sniffed:`, `record`.