Stream Data And Errors Across io.Pipe
Copy bytes from a producer goroutine through io.Pipe and propagate failures explicitly via CloseWithError instead of a silent EOF.
Code
package main
import (
"bytes"
"errors"
"fmt"
"io"
)
func streamWithFailure(chunks []string, failAfter int) (string, error) {
pr, pw := io.Pipe()
errAborted := errors.New("upstream checksum mismatch")
go func() {
for i, chunk := range chunks {
if i == failAfter {
// Propagate exact error to the reader instead of silent EOF
_ = pw.CloseWithError(errAborted)
return
}
if _, err := io.WriteString(pw, chunk); err != nil {
_ = pw.CloseWithError(err)
return
}
}
_ = pw.Close()
}()
var dst bytes.Buffer
_, err := io.Copy(&dst, pr)
_ = pr.Close()
return dst.String(), err
}
func main() {
data, err := streamWithFailure([]string{"head:", "body:", "tail"}, -1)
fmt.Printf("ok stream=%q err=%v\n", data, err)
partial, err := streamWithFailure([]string{"head:", "body:", "tail"}, 2)
fmt.Printf("failed partial=%q err=%v\n", partial, err)
}Runtime walkthrough — Stream Data And Errors Across io.Pipe
Structurally, expect the functions streamWithFailure and main and nothing else.
Repetition is confined to for i, chunk := range chunks — the rest of the file is straight-line. Error handling is inline: 1 place test err != nil and branch immediately. Work is dispatched on a goroutine.
Caveats
- Pure standard library code — paste it straight into your file and execute.
- There are no exceptions to catch —
errreturn values must be checked at each call site.
Putting it to use
Entry signature: func streamWithFailure(chunks []string, failAfter int) (string, error)
The demo output is labeled (ok stream=, failed partial=); each label names the call that printed it.
The demo flow inside main is streamWithFailure — run the file to see it end to end.
Core lines
for i, chunk := range chunks {
if i == failAfter {
// Propagate exact error to the reader instead of silent EOF
_ = pw.CloseWithError(errAborted)
return
}
if _, err := io.WriteString(pw, chunk); err != nil {
_ = pw.CloseWithError(err)
return
}
}
func main() {
data, err := streamWithFailure([]string{"head:", "body:", "tail"}, -1)
fmt.Printf("ok stream=%q err=%v\n", data, err)
partial, err := streamWithFailure([]string{"head:", "body:", "tail"}, 2)
fmt.Printf("failed partial=%q err=%v\n", partial, err)
}
errAborted := errors.New("upstream checksum mismatch")
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- As returned `error` values — 1 site in the snippet check `err` before using other results.
- What does Stream Data And Errors Across io.Pipe print when run?
- Run it as a complete program — the output lines carry labels such as `ok stream=`, `failed partial=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.