Read stdin and stream output
Read stdin and stream output
A filter reads stdin and writes transformed data to stdout. Process one line at a time instead of loading the entire input. Use io.Reader and io.Writer so the same function works with files, pipes and test buffers.
package main
import ( "bufio" "fmt" "io" "os" "strings")
func upper(in io.Reader, out io.Writer) error { s := bufio.NewScanner(in) s.Buffer(make([]byte, 0, 64), 1024) for s.Scan() { if _, err := fmt.Fprintln(out, strings.ToUpper(s.Text())); err != nil { return err } } return s.Err()}func main() { if err := upper(strings.NewReader("go\ncli\n"), os.Stdout); err != nil { panic(err) }}Scan returns false on EOF or error; Err distinguishes these cases. Text excludes the line delimiter; Fprintln adds a newline even for a final unterminated line. Connect upper(os.Stdin, os.Stdout) in a real command. This is a line transformer, not a byte-preserving copy.
Expected output:
GOCLIBound record size
package main
import ( "bufio" "bytes" "fmt" "io" "strings")
func upper(in io.Reader, out io.Writer) error { s := bufio.NewScanner(in) s.Buffer(make([]byte, 0, 64), 1024) for s.Scan() { if _, err := fmt.Fprintln(out, strings.ToUpper(s.Text())); err != nil { return err } } return s.Err()}func main() { var out bytes.Buffer err := upper(strings.NewReader("ok\n"+strings.Repeat("x", 2048)), &out) fmt.Print(out.String()) fmt.Println(err != nil)}Buffer sets a maximum token buffer, not an exact maximum line length because delimiters may occupy space. Earlier output may already be visible when a later record fails. Report the failure; a pipe cannot be rolled back. Atomic output requires a separate staging and commit strategy.
Expected output:
OKtrueTry it locally
Check empty input, then process a final line without a newline.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 04: Read stdin and stream output
Check the lesson objective before moving on.
Why check Scanner.Err after the loop?
What happens if a later record fails?