Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Last active November 21, 2024 02:12
Show Gist options
  • Save ValentaTomas/ef71450c9093e9ef61d1d5b23eb31ede to your computer and use it in GitHub Desktop.
Save ValentaTomas/ef71450c9093e9ef61d1d5b23eb31ede to your computer and use it in GitHub Desktop.
Resend the same value to several places without handling subscribers. (Not recommended for production.)
type Tunnel[T any] struct {
ch chan T
}
func (t *Tunnel[T]) Send(ctx context.Context, value T) error {
select {
case t.ch <- value:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (t *Tunnel[T]) Recv(ctx context.Context) (T, error) {
select {
case value := <-t.ch:
go func() {
t.ch <- value
}()
return value, nil
case <-ctx.Done():
var zero T
return zero, ctx.Err()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment