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.
Code
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
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.HTTP Header AnalyzerPaste raw HTTP header lines and get a parsed name-value list with plain-language notes for common headers and security observations.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.