Go:Go Stdin Input: Streaming Lines with bufio.NewScanner(os.Stdin)
Go•Stdin Parsing

Go Stdin Input: Streaming Lines with bufio.NewScanner(os.Stdin)

In Compilra Go 1.23, all standard input is provided in the Stdin panel before clicking Run. Using bufio.NewScanner(os.Stdin) lets you iterate cleanly line-by-line, split arbitrary whitespace with strings.Fields, and inspect any I/O error afterward.

Syntax

scanner := bufio.NewScanner(os.Stdin); for scanner.Scan() { line := scanner.Text() }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
bufio.NewScanner(os.Stdin)*bufio.ScannerCreates a buffered scanner over os.Stdin that reads one line per Scan() call.
strings.Fields()[]stringSplits a line on one or more consecutive whitespace characters cleanly.
scanner.Err()errorReturns the first non-EOF error encountered while scanning stdin.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    count := 0
    totalLatency := 0

    for scanner.Scan() {
        line := strings.TrimSpace(scanner.Text())
        if line == "" {
            continue
        }
        fields := strings.Fields(line)
        service := fields[0]
        status := fields[1]
        ms, _ := strconv.Atoi(fields[2])

        count++
        totalLatency += ms
        fmt.Printf("[%d] %s -> HTTP %s (%dms)\n", count, service, status, ms)
    }

    if err := scanner.Err(); err != nil {
        fmt.Fprintf(os.Stderr, "read error: %v\n", err)
    }
    fmt.Printf("Processed %d logs, total latency: %dms\n", count, totalLatency)
}
Pre-Supplied Stdin (Input):
auth-api 200 14
payments 503 120
search 200 32
Expected Output:
[1] auth-api -> HTTP 200 (14ms)
[2] payments -> HTTP 503 (120ms)
[3] search -> HTTP 200 (32ms)
Processed 3 logs, total latency: 166ms

How It Works: Step-by-Step

  • Lines 12-20: Initializes bufio.NewScanner(os.Stdin), loops with scanner.Scan(), and skips blank lines.
  • Lines 21-28: Splits each log entry with strings.Fields and converts the millisecond token using strconv.Atoi.
  • Lines 31-34: Checks scanner.Err() after EOF and prints the aggregate latency summary.

Key Concepts

  • Provide all lines in Compilra’s Standard Input (stdin) panel before clicking Run—input is passed upfront to os.Stdin.
  • strings.Fields handles tabs and extra spaces automatically, unlike strings.Split(line, " ").
  • Always check scanner.Err() after the scan loop finishes so silent read errors never go unnoticed.

Common Mistake: Ignoring scanner.Err() or using strings.Split(line, " ") on irregular spacing

strings.Split(line, " ") produces empty strings on double spaces, whereas strings.Fields collapses all whitespace.

❌ Incorrect
parts := strings.Split("api  200", " ") // ["api", "", "200"]!
✅ Correct
parts := strings.Fields("api  200") // ["api", "200"]

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler