Combine readers and writers
Combine readers and writers
io.MultiReader presents several readers as one stream in order. io.MultiWriter writes to several destinations in order. io.TeeReader mirrors the bytes actually consumed by a reader. These wrappers allow existing I/O functions to work with composed streams.
package main
import ( "bytes" "fmt" "io" "strings")
func main() { r := io.MultiReader(strings.NewReader("head:"), strings.NewReader("body")) var a, b bytes.Buffer n, err := io.Copy(io.MultiWriter(&a, &b), r) fmt.Println(n, err == nil) fmt.Println(a.String(), b.String())}MultiReader advances to the next reader after EOF. MultiWriter stops at the first error; earlier writes may remain. This is not a transaction. These wrappers do not close the underlying resources.
Expected output:
9 truehead:body head:bodyMirror consumed bytes
package main
import ( "bytes" "fmt" "io" "strings")
func main() { var mirror bytes.Buffer r := io.TeeReader(strings.NewReader("abcdef"), &mirror) p := make([]byte, 3) n, err := io.ReadFull(r, p) fmt.Println(string(p[:n]), err == nil, mirror.String())}TeeReader has no internal buffering: its write completes before the read completes. Only abc was consumed. A mirror write error appears as a read error. Avoid logging sensitive payloads indiscriminately.
Expected output:
abc true abcTry it locally
Combine readers containing "red" and "-blue". Copy to two buffers with MultiWriter. Print byte count, success and both results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 05: Combine readers and writers
Check the lesson objective before moving on.
What happens when the second MultiWriter destination fails?
When does TeeReader mirror bytes?