Peek And Read With bufio.Reader
Inspect upcoming bytes with Peek without consuming them, then ReadString and drain the rest, the core moves for line-based protocol parsing.
Code
package main
import (
"bufio"
"errors"
"fmt"
"io"
"strings"
)
func main() {
// 一条多行协议:第一行是命令,其余是负载
input := strings.NewReader("SET key=value\npayload-bytes\n")
reader := bufio.NewReader(input)
// Peek:偷看前 4 字节但不消费,适合协议探测
head, err := reader.Peek(4)
if err != nil {
panic(err)
}
fmt.Printf("peek: %q (nothing consumed yet)\n", head)
// ReadString:读到分隔符为止,返回值含分隔符本身
line, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
panic(err)
}
fmt.Printf("command: %s", line)
rest, err := io.ReadAll(reader)
if err != nil {
panic(err)
}
fmt.Printf("payload: %q\n", string(rest))
}What the code shows
The snippet feeds a two-line protocol string into bufio.NewReader and works through it in three moves: Peek(4) inspects the first four bytes without consuming them, ReadString(‘\n’) pulls the command line including its newline, and io.ReadAll drains whatever payload follows. The Peek result is printed with %q so the not-yet-consumed bytes are visible in the output.
Failure paths
- A Peek error goes straight to panic(err) — the four-byte head is required before the run makes sense.
- ReadString treats io.EOF as a normal end via errors.Is(err, io.EOF), because the final line may arrive without a trailing newline.
- Any other error from ReadString or io.ReadAll also aborts with panic.
Reading the output
The run labels its three stages with the prefixes peek:, command:, and payload:. Because Peek consumed nothing, the command line still contains the full SET key=value text, and the payload stage captures payload-bytes as the leftover.
Interactive Tools for This Topic
FAQ
- Does Peek consume the bytes it returns?
- No. Peek copies the next bytes out of the buffer without advancing it, so the later ReadString('\n') still sees the complete first line of the protocol.
- Why is io.EOF special-cased for ReadString?
- When input ends before the delimiter, ReadString returns the partial line plus io.EOF. errors.Is(err, io.EOF) accepts that as a finished command instead of aborting the run.
Report a problem with this exampleOpens a pre-filled issue on GitHub.