Created
January 23, 2022 14:43
-
-
Save abdusco/92e17dfa67a2ebc119f77c010618b480 to your computer and use it in GitHub Desktop.
Hub implementation in Go
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
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