package main import ( "context" "sync" "github.com/coder/websocket" ) type hub struct { mu sync.Mutex conns map[string]map[*websocket.Conn]struct{} } func newHub() *hub { return &hub{conns: make(map[string]map[*websocket.Conn]struct{})} } func (h *hub) add(listID string, c *websocket.Conn) { h.mu.Lock() defer h.mu.Unlock() if h.conns[listID] == nil { h.conns[listID] = make(map[*websocket.Conn]struct{}) } h.conns[listID][c] = struct{}{} } func (h *hub) remove(listID string, c *websocket.Conn) { h.mu.Lock() defer h.mu.Unlock() delete(h.conns[listID], c) if len(h.conns[listID]) == 0 { delete(h.conns, listID) } } func (h *hub) broadcast(listID string) { h.mu.Lock() conns := make([]*websocket.Conn, 0, len(h.conns[listID])) for c := range h.conns[listID] { conns = append(conns, c) } h.mu.Unlock() for _, c := range conns { go c.Write(context.Background(), websocket.MessageText, []byte("changed")) } }