OrDone Wraps Channel Cancellation

Wrap a producer channel with orDone so a downstream consumer can cancel mid-stream while the wrapper and the producer both exit instead of leaking.

GoResilience

Code

gosnippet
56 lines
package main

import "fmt"

// orDone 把下游取消 cancellation 与上游关闭统一成一个可 range 的通道。
// 包装后消费者 range 的还是一个普通 channel,但 done 一关整条链路都能退出
func orDone(done <-chan struct{}, in <-chan string) <-chan string {
	out := make(chan string)
	go func() {
		defer close(out)
		for {
			select {
			case <-done:
				return
			case v, ok := <-in:
				if !ok {
					return
				}
				select {
				case out <- v:
				case <-done:
					return
				}
			}
		}
	}()
	return out
}

func main() {
	done := make(chan struct{})
	jobs := make(chan string)

	// 无界生产者:只在发送成功或 done 关闭时继续
	go func() {
		defer close(jobs)
		for i := 1; ; i++ {
			select {
			case jobs <- fmt.Sprintf("job-%d", i):
			case <-done:
				return
			}
		}
	}()

	received := 0
	for v := range orDone(done, jobs) {
		fmt.Println("processed:", v)
		received++
		if received == 3 {
			close(done)
			break // 停止接收后,包装层经 done 退出并关闭 out,生产者随之解阻
		}
	}
	fmt.Println("stopped after", received)
}

How the code works

The code doing the work is the functions orDone and main — everything else is wiring.

Repetition is confined to for — the rest of the file is straight-line. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Watch out for

  • The dependency list is empty; the language runtime covers it all.

Applying it

The one signature in play: func orDone(done <-chan struct{}, in <-chan string) <-chan string

Output lines are prefixed (processed:, stopped after), so every printed result carries the label of its step.

The demo flow inside main is orDone — run the file to see it end to end.

Statements that matter

for v := range orDone(done, jobs) {
	fmt.Println("processed:", v)
	received++
	if received == 3 {
		close(done)
		break // 停止接收后,包装层经 done 退出并关闭 out,生产者随之解阻
	}
}
done := make(chan struct{})
jobs := make(chan string)

Interactive Tools for This Topic

FAQ

What does OrDone Wraps Channel Cancellation print when run?
Run it as a complete program — the output lines carry labels such as `processed:`, `stopped after`.