Last active
October 21, 2023 17:32
-
-
Save snorremd/635d71f013c9956dec9c2bb55b839b5d to your computer and use it in GitHub Desktop.
Go Broadcast solution
This file contains hidden or 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
// 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