Scanner Buffer For Oversized Lines
A Scanner stops with token too long once a line exceeds 64KB; Buffer raises the cap so oversized log lines stream through without crashing.
Code
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
// 一行 100KB:超过 Scanner 默认的 64KB 单行上限
huge := strings.Repeat("x", 100_000)
input := strings.NewReader(huge + "\ntail\n")
scanner := bufio.NewScanner(input)
for scanner.Scan() {
fmt.Printf("read line of %d bytes\n", len(scanner.Text()))
}
// Scan 在超长行处停下,原因只在 Err():bufio.Scanner: token too long
if err := scanner.Err(); err != nil {
fmt.Println("default limit:", err)
}
// scanner.Buffer 提高上限:初始缓冲 1KB,允许最长 1MB
scanner = bufio.NewScanner(strings.NewReader(huge + "\ntail\n"))
scanner.Buffer(make([]byte, 0, 1024), 1<<20)
for scanner.Scan() {
fmt.Printf("read line of %d bytes\n", len(scanner.Text()))
}
if err := scanner.Err(); err != nil {
fmt.Println("with buffer:", err)
}
}How the snippet works
Scanner Buffer For Oversized Lines is built around the function main.
Repetition is confined to for scanner.Scan() — the rest of the file is straight-line. Nothing falls through silently — 2 checkpoints test err != nil on the way through.
Caveats
- No install step stands between you and running this: standard library only.
Applying it
Look for the read line of, default limit:, with buffer: prefixes when the file runs; they tie each line to its step.
Statements that carry the weight
if err := scanner.Err(); err != nil {
fmt.Println("default limit:", err)
}
if err := scanner.Err(); err != nil {
fmt.Println("with buffer:", err)
}
scanner.Buffer(make([]byte, 0, 1024), 1<<20)
Interactive Tools for This Topic
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Scanner Buffer For Oversized Lines print when run?
- Run it as a complete program — the output lines carry labels such as `read line of`, `default limit:`, `with buffer:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.