The obvious place to start with IO is, well, the io
package (https://golang.org/pkg/io). As we have already seen, the io
package defines input and output primitives as the io.Reader
and io.Writer
interfaces. The following table summarizes additional functions and types, available in the io
package, that facilitate streaming IO operations.
Function |
Description |
|
The data := strings.NewReader("Write me down.") file, _ := os.Create("./iocopy.data") io.Copy(file, data)
golang.fyi/ch10/iocopy.go |
|
The file, _ := os.Create("./iopipe.data") pr, pw := io.Pipe() go func() { fmt.Fprint(pw, "Pipe streaming") pw.Close() }() wait := make(chan struct{}) go func() { io.Copy(file, pr) pr.Close() close(wait) }() <-wait //wait for pr to finish
golang.fyi/ch10/iopipe.go
Note that the pipe writer will block until the reader completely consumes the pipe content or an error is encountered. Therefore, both the reader and writer should be wrapped in a goroutine to avoid deadlocks. |
|
Similar to the
The TeeReader works well for composing multi-step IO stream processing. The following abbreviated snippet first calculates the SHA-1 hash of a file content using the
fin, _ := os.Open("./ioteerdr.go") defer fin.Close() fout, _ := os.Create("./teereader.gz") defer fout.Close() zip := gzip.NewWriter(fout) defer zip.Close() sha := sha1.New() data := io.TeeReader(fin, sha) io.Copy(zip, data) fmt.Printf("SHA1 hash %x ", sha.Sum(nil))
golang.fyi/ch10/ioteerdr0.go
If we wanted to calculate both SHA-1 and MD5, we can update the code to nest the two
sha := sha1.New() md := md5.New() data := io.TeeReader( io.TeeReader(fin, md), sha, ) io.Copy(zip, data)
golang.fyi/ch10/ioteerdr1.go |
|
The fout, err := os.Create("./iowritestr.data") if err != nil { fmt.Println(err) os.Exit(1) } defer fout.Close() io.WriteString(fout, "Hello there! ")
golang.fyi/ch10/iowritestr.go |
|
As its name suggests, the str := strings.NewReader("The quick brown " + "fox jumps over the lazy dog") limited := &io.LimitedReader{R: str, N: 19} io.Copy(os.Stdout, limited)
golang.fyi/ch10/iolimitedrdr.go
$> go run iolimitedrd.go The quick brown fox |
|
The str := strings.NewReader("The quick brown"+ "fox jumps over the lazy dog") section := io.NewSectionReader(str, 19, 23) io.Copy(os.Stdout, section)
golang.fyi/ch10/iosectionrdr.go
This example will print |
Package |
The |
3.145.179.85