Connect Goroutines With io.Pipe

io.Pipe hands bytes between goroutines synchronously: each Write blocks until the reader takes it, and the writer must Close to end the stream.

GoResilience

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"io"
)

func main() {
	// io.Pipe:同步内存管道,Write 会阻塞到 Read 取走数据
	pr, pw := io.Pipe()

	go func() {
		// 写完必须 Close,否则读取方永远阻塞在等待流结束
		fmt.Fprint(pw, "chunk-1\n")
		fmt.Fprint(pw, "chunk-2\n")
		pw.Close()
	}()

	data, err := io.ReadAll(pr)
	if err != nil {
		panic(err)
	}
	fmt.Print(string(data))
	fmt.Println("bytes:", len(data))
}

Under the hood

Connect Goroutines With io.Pipe reduces to the function main.

Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err). Work is dispatched on a goroutine.

What to watch for

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Applying it

The demo output is labeled (bytes:), so every printed line maps back to its originating operation.

Statements that matter

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
What does Connect Goroutines With io.Pipe print when run?
Run it as a complete program — the output lines carry labels such as `bytes:`.