Go 1.27 reference · Files, HTTP and Logging
Go bufio.Scanner Type
Read input line by line (or word by word) from a file, string or stdin without loading it all into memory.
Go 1.27
Syntax
func NewScanner(r io.Reader) *Scanner
Parameters
| Parameter | Description |
|---|---|
Scan() / Text() |
Advance and read the current token. |
Split(bufio.ScanWords) |
Tokens other than lines. |
Buffer(buf, max) |
Allow lines longer than 64 KB. |
Err() |
Check after the loop. |
Examples
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
input := "GET /\nPOST /orders\nGET /health\n"
sc := bufio.NewScanner(strings.NewReader(input))
gets := 0
for sc.Scan() {
if strings.HasPrefix(sc.Text(), "GET") {
gets++
}
}
fmt.Println("GET requests:", gets, "error:", sc.Err())
}
Output
GET requests: 2 error: <nil>
Run this on your computer — see “Get Started” for setup.
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
sc := bufio.NewScanner(strings.NewReader("the quick brown fox"))
sc.Split(bufio.ScanWords)
n := 0
for sc.Scan() {
n++
}
fmt.Println(n, "words")
}
Output
4 words
Run this on your computer — see “Get Started” for setup.
Related
os.ReadFile and os.WriteFile· Read or write a whole file in one call, with Unix permissions for new files; errors wrap fs.ErrNotExist and friends.- Go File Handling · tutorial