94 lines
1.5 KiB
Go
94 lines
1.5 KiB
Go
package drop
|
|
|
|
import (
|
|
"encoding/json"
|
|
"sync"
|
|
)
|
|
|
|
type Client struct {
|
|
ID string
|
|
UserID string
|
|
conn *websocketConn
|
|
send chan []byte
|
|
}
|
|
|
|
type Hub struct {
|
|
mu sync.RWMutex
|
|
clients map[string]*Client
|
|
byUser map[string]string
|
|
}
|
|
|
|
func NewHub() *Hub {
|
|
return &Hub{
|
|
clients: map[string]*Client{},
|
|
byUser: map[string]string{},
|
|
}
|
|
}
|
|
|
|
func (h *Hub) Add(client *Client) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
h.clients[client.ID] = client
|
|
h.byUser[client.UserID] = client.ID
|
|
}
|
|
|
|
func (h *Hub) Remove(clientID string) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
client := h.clients[clientID]
|
|
if client != nil {
|
|
delete(h.byUser, client.UserID)
|
|
close(client.send)
|
|
}
|
|
delete(h.clients, clientID)
|
|
}
|
|
|
|
func (h *Hub) Send(clientID string, event any) {
|
|
payload, err := json.Marshal(event)
|
|
if err != nil {
|
|
return
|
|
}
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
client := h.clients[clientID]
|
|
if client == nil {
|
|
return
|
|
}
|
|
select {
|
|
case client.send <- payload:
|
|
default:
|
|
}
|
|
}
|
|
|
|
func (h *Hub) SendToUser(userID string, event any) {
|
|
h.mu.RLock()
|
|
clientID := h.byUser[userID]
|
|
h.mu.RUnlock()
|
|
if clientID != "" {
|
|
h.Send(clientID, event)
|
|
}
|
|
}
|
|
|
|
func (h *Hub) Broadcast(event any) {
|
|
payload, err := json.Marshal(event)
|
|
if err != nil {
|
|
return
|
|
}
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
for _, client := range h.clients {
|
|
select {
|
|
case client.send <- payload:
|
|
default:
|
|
}
|
|
}
|
|
}
|
|
|
|
func (c *Client) writeLoop() {
|
|
for payload := range c.send {
|
|
if err := c.conn.WriteText(payload); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|