How to Implement the Tee Channel Pattern in Go
The Tee Channel pattern is implemented by creating a goroutine that reads from a source channel and writes to multiple destination channels until the source closes.
func tee[T any](src <-chan T, dests ...chan<- T) {
defer func() {
for _, d := range dests {
close(d)
}
}()
for v := range src {
for _, d := range dests {
d <- v
}
}
}
This pattern duplicates data from one channel to many, ensuring all destinations receive the same stream of values and are closed when the source ends.