cleaner approach to line-filter. fixes #18
This commit is contained in:
parent
58b809110d
commit
aea5979e91
@ -8,26 +8,26 @@
|
|||||||
// 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, and
|
// Package `bufio` will help us read line-by-line.
|
||||||
// `bytes` provides the byte-level capitalization
|
|
||||||
// function.
|
|
||||||
import "bufio"
|
import "bufio"
|
||||||
import "bytes"
|
import "strings"
|
||||||
import "os"
|
import "os"
|
||||||
import "io"
|
import "io"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
// Wrapping the unbuffered `os.Stdin` with a buffered
|
// Wrapping the unbuffered `os.Stdin` with a buffered
|
||||||
// reader gives us the convenient `ReadLine` method.
|
// reader gives us a convenient `ReadString` method
|
||||||
|
// that we'll use to read input line-by-line.
|
||||||
in := bufio.NewReader(os.Stdin)
|
in := bufio.NewReader(os.Stdin)
|
||||||
out := os.Stdout
|
out := os.Stdout
|
||||||
|
|
||||||
// Each `ReadLine` call returns bytes of read data and
|
// `ReadString` returns the next string from the
|
||||||
// a boolean indicating if we don't have the whole
|
// input up to the given separator byte. We give the
|
||||||
// line yet, or an error.
|
// newline byte `'\n'` as our separator so we'll get
|
||||||
|
// successive input lines.
|
||||||
for {
|
for {
|
||||||
inBytes, pfx, err := in.ReadLine()
|
inLine, err := in.ReadString('\n')
|
||||||
|
|
||||||
// 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.
|
||||||
@ -39,18 +39,12 @@ func main() {
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write out the uppercased bytes, checking for an
|
// Write out the uppercased line, checking for an
|
||||||
// error on the write as we did on the read.
|
// error on the write as we did on the read.
|
||||||
outBytes := bytes.ToUpper(inBytes)
|
outLine := strings.ToUpper(inLine)
|
||||||
_, err = out.Write(outBytes)
|
_, err = out.WriteString(outLine)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unless this read was for a prefix (not the full
|
|
||||||
// line), we need to add our own newline.
|
|
||||||
if !pfx {
|
|
||||||
out.WriteString("\n")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user