package hub import ( "sync" "github.com/gorilla/websocket" ) // Hub 管理 WebSocket 客户端连接 type Hub struct { mu sync.RWMutex clients map[string]map[*websocket.Conn]bool // userID -> connections } func NewHub() *Hub { return &Hub{ clients: make(map[string]map[*websocket.Conn]bool), } } func (h *Hub) Register(userID string, conn *websocket.Conn) { h.mu.Lock() defer h.mu.Unlock() if h.clients[userID] == nil { h.clients[userID] = make(map[*websocket.Conn]bool) } h.clients[userID][conn] = true } func (h *Hub) Unregister(userID string, conn *websocket.Conn) { h.mu.Lock() defer h.mu.Unlock() if conns, ok := h.clients[userID]; ok { delete(conns, conn) if len(conns) == 0 { delete(h.clients, userID) } } } // SendToUser 向指定用户的所有连接推送消息 func (h *Hub) SendToUser(userID string, message []byte) error { h.mu.RLock() defer h.mu.RUnlock() conns, ok := h.clients[userID] if !ok { return nil } for conn := range conns { if err := conn.WriteMessage(websocket.TextMessage, message); err != nil { return err } } return nil }