f5219f3c68
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
52 lines
890 B
Go
52 lines
890 B
Go
package websocket
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"sync"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
type Hub struct {
|
|
mu sync.RWMutex
|
|
clients map[*websocket.Conn]struct{}
|
|
}
|
|
|
|
func NewHub() *Hub {
|
|
return &Hub{clients: make(map[*websocket.Conn]struct{})}
|
|
}
|
|
|
|
func (h *Hub) Register(conn *websocket.Conn) {
|
|
h.mu.Lock()
|
|
h.clients[conn] = struct{}{}
|
|
h.mu.Unlock()
|
|
}
|
|
|
|
func (h *Hub) Unregister(conn *websocket.Conn) {
|
|
h.mu.Lock()
|
|
delete(h.clients, conn)
|
|
h.mu.Unlock()
|
|
}
|
|
|
|
func (h *Hub) Broadcast(msg interface{}) {
|
|
data, err := json.Marshal(msg)
|
|
if err != nil {
|
|
log.Printf("[ws] marshal: %v", err)
|
|
return
|
|
}
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
for conn := range h.clients {
|
|
if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
|
|
log.Printf("[ws] write: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *Hub) Count() int {
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
return len(h.clients)
|
|
}
|