Read stdin lines
Read standard input line by line in Go with bufio.Scanner. It strips the newline, handles a last line without one, and stops with an error on very long lines.
A Go program should read its input line by line, the way while read does in a shell.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
n := 0
for sc.Scan() {
n++
fmt.Printf("%d: [%s]\n", n, sc.Text())
}
if err := sc.Err(); err != nil {
fmt.Fprintln(os.Stderr, "read error:", err)
os.Exit(1)
}
}printf 'first\n indented line\n\nlast without newline' | go run main.go1: [first]
2: [ indented line]
3: []
4: [last without newline]Scan advances to the next token, which is a line by default, and Text returns it without the trailing newline. Leading spaces, empty lines and a final line with no newline are all kept as they are, as the output shows. The bufio.Scanner documentation says to check Err after the loop, because Scan returns false on a read error as well as at the end of the input.
A line longer than 64 KiB makes the scanner stop with bufio.Scanner: token too long, and the loop ends without processing the rest. Raise the limit with sc.Buffer(make([]byte, 0, 64*1024), 1<<20) before the first Scan, or read with bufio.Reader.ReadString for unbounded lines.