Merge pull request #22 from mmcgrana/idiomatic-line-filters

Idiomatic line filters
This commit is contained in:
Mark McGranaghan 2012-10-16 10:38:33 -07:00
commit 87fa837f18

View File

@ -8,18 +8,20 @@
// pattern to write your own Go line filters. // pattern to write your own Go line filters.
package main package main
// Package `bufio` will help us read line-by-line. import (
import "bufio" "bufio"
import "strings" "fmt"
import "os" "io"
import "io" "os"
"strings"
)
func main() { func main() {
// Wrapping the unbuffered `os.Stdin` with a buffered // Wrapping the unbuffered `os.Stdin` with a buffered
// reader gives us a convenient `ReadString` method // reader gives us a convenient `ReadString` method
// that we'll use to read input line-by-line. // that we'll use to read input line-by-line.
in := bufio.NewReader(os.Stdin) rdr := bufio.NewReader(os.Stdin)
out := os.Stdout out := os.Stdout
// `ReadString` returns the next string from the // `ReadString` returns the next string from the
@ -27,24 +29,28 @@ func main() {
// newline byte `'\n'` as our separator so we'll get // newline byte `'\n'` as our separator so we'll get
// successive input lines. // successive input lines.
for { for {
inLine, err := in.ReadString('\n') switch line, err := rdr.ReadString('\n'); err {
// If the read succeeded (the read `err` is nil),
// write out out the uppercased line. Check for an
// error on this write as we do on the read.
case nil:
ucl := strings.ToUpper(line)
if _, err = out.WriteString(ucl); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
// The `EOF` error is expected when we reach the // The `EOF` error is expected when we reach the
// end of input, so exit gracefully in that case. // end of input, so exit gracefully in that case.
// Otherwise there's a problem. case io.EOF:
if err == io.EOF { os.Exit(0)
return
}
if err != nil {
panic(err)
}
// Write out the uppercased line, checking for an // Otherwise there's a problem; print the
// error on the write as we did on the read. // error and exit with non-zero status.
outLine := strings.ToUpper(inLine) default:
_, err = out.WriteString(outLine) fmt.Fprintln(os.Stderr, "error:", err)
if err != nil { os.Exit(1)
panic(err)
} }
} }
} }