Skip to content

Instantly share code, notes, and snippets.

@snorremd
Last active October 21, 2023 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snorremd/635d71f013c9956dec9c2bb55b839b5d to your computer and use it in GitHub Desktop.
Save snorremd/635d71f013c9956dec9c2bb55b839b5d to your computer and use it in GitHub Desktop.
Go Broadcast solution
// Make it extend sync to handle multiple go routines
type Broadcaster struct {
sync.Mutex
clients map[string]chan models.CreatePostEvent
}
// Constructor
func NewBroadcaster() *Broadcaster {
return &Broadcaster{
clients: make(map[string]chan models.CreatePostEvent),
}
}
func (b *Broadcaster) Broadcast(post models.CreatePostEvent) {
b.Lock()
defer b.Unlock()
for _, client := range b.clients {
client <- post
}
}
// Function to add a client to the broadcaster
func (b *Broadcaster) AddClient(key string, client chan models.CreatePostEvent) {
b.Lock()
defer b.Unlock()
b.clients[key] = client
}
// Function to remove a client from the broadcaster
func (b *Broadcaster) RemoveClient(key string) {
b.Lock()
defer b.Unlock()
delete(b.clients, key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment