Skip to content

Instantly share code, notes, and snippets.

@abdusco
Created January 23, 2022 14:43
Show Gist options
  • Save abdusco/92e17dfa67a2ebc119f77c010618b480 to your computer and use it in GitHub Desktop.
Save abdusco/92e17dfa67a2ebc119f77c010618b480 to your computer and use it in GitHub Desktop.
Hub implementation in Go
type Subscriber struct {
send chan string
}
type Hub struct {
clients map[*Subscriber]bool
broadcast chan string
register chan *Subscriber
unregister chan *Subscriber
}
func NewHub() *Hub {
return &Hub{
clients: make(map[*Subscriber]bool),
broadcast: make(chan string),
register: make(chan *Subscriber),
unregister: make(chan *Subscriber),
}
}
func (h *Hub) Run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
delete(h.clients, client)
close(client.send)
case msg := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- msg:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment