liveBook · Manning

Bufio

As explained in Go in Practice, Second Edition

The Go bufio package provides buffered input and output wrappers and utilities for processing streams incrementally.

The Go bufio package wraps Readers and Writers with buffering for efficient, incremental stream processing. It is especially useful when large files should be processed without loading everything into memory. section 7.1.1

For newline-delimited JSON, bufio.Scanner combined with bufio.ScanLines reads one record at a time. Each line can be unmarshaled independently, allowing invalid entries to be logged and skipped while processing continues. section 7.1.1

Listing 7.4 Using bufio to read line by line
package main

import (
    "bufio"
    "encoding/json"
    "log"
    "os"
)

func main() {
    file, err := os.Open("structured.log")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    scan := bufio.NewScanner(file)        #1
    scan.Split(bufio.ScanLines)                 #2
    lineJSON := make(map[string]interface{})
    for scan.Scan() {                          #3
        if err := json.Unmarshal([]byte(scan.Text()), &lineJSON); err != n
        il {
            log.Println(err)
        } else {
            log.Println(lineJSON["level"])
        }
    }
}

Shows a complete Go program that opens structured.log, configures line scanning, unmarshals each record, and prints its level. section 7.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Demonstrates Scanner and ScanLines in runnable code, while deferring deeper optimization and distributed processing.
Examples
Uses a structured.log file containing newline-delimited JSON records and extracts each record's level.
What it assumes
Assumes familiarity with Go files, JSON unmarshaling, and Readers while demonstrating the buffered scanning pattern directly.
What you can do after
Build line-oriented Go processors that scan files incrementally and handle malformed records without stopping the entire stream.
How it connects
Connects buffered I/O with Readers, Writers, streaming, JSON, CSV, and concurrent or distributed file processing.

Also explained in

Compare how 2 books explain bufio →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.