Last active
January 26, 2021 14:24
-
-
Save strideynet/075323c345415fedc9aa3879fcbb286c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"sync" | |
) | |
type BroadcastManager struct { | |
sync.Mutex | |
subs map[chan string]struct{} | |
} | |
func (b *BroadcastManager) Broadcast(text string) { | |
b.Lock() | |
defer b.Unlock() | |
for ch := range b.subs { | |
ch <- text | |
} | |
} | |
func (b *BroadcastManager) Subscribe() (chan string, func()) { | |
b.Lock() | |
defer b.Unlock() | |
ch := make(chan string) | |
b.subs[ch] = struct{}{} | |
return ch, func() { | |
b.Lock() | |
defer b.Unlock() | |
delete(b.subs, ch) | |
} | |
} | |
var instanceOfBm = &BroadcastManager{ | |
Mutex: sync.Mutex{}, | |
subs: map[chan string]struct{}{}, | |
} | |
type Sender interface { | |
Send(string) error | |
} | |
func handleIncomingGRPCStreamRequest(ctx context.Context, s Sender) error { | |
ch, cancel := instanceOfBm.Subscribe() | |
defer cancel() | |
for { | |
select { | |
case <-ctx.Done(): | |
break | |
case msg := <-ch: | |
if err := s.Send(msg); err != nil { | |
return err | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment