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:
| Parameter | Type | Description |
|---|---|---|
| bufio.NewScanner(os.Stdin) | *bufio.Scanner | Creates a buffered scanner over os.Stdin that reads one line per Scan() call. |
| strings.Fields() | []string | Splits a line on one or more consecutive whitespace characters cleanly. |
| scanner.Err() | error | Returns the first non-EOF error encountered while scanning stdin. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Go Console I/O: fmt.Print, fmt.Println, and fmt.Printf
Format output and read inputs using Go standard library fmt package.
Go Type Conversion and strconv Package (Atoi, Itoa)
Convert numeric types and parse strings using strconv.Atoi and strconv.Itoa.
Go Strings, Runes, and the strings Package
Understand UTF-8 encoded strings, runes (Unicode code points), and strings package functions.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.