summaryrefslogtreecommitdiff
path: root/internal/api/websocket.go
blob: 6bd8c880348224cafe61487fcec679bebbd0788f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package api

import (
	"log/slog"
	"net/http"
	"sync"

	"golang.org/x/net/websocket"
)

// Hub manages WebSocket connections and broadcasts messages.
type Hub struct {
	mu      sync.RWMutex
	clients map[*websocket.Conn]bool
	logger  *slog.Logger
}

func NewHub() *Hub {
	return &Hub{
		clients: make(map[*websocket.Conn]bool),
		logger:  slog.Default(),
	}
}

// Run is a no-op loop kept for future cleanup/heartbeat logic.
func (h *Hub) Run() {}

func (h *Hub) Register(ws *websocket.Conn) {
	h.mu.Lock()
	h.clients[ws] = true
	h.mu.Unlock()
}

func (h *Hub) Unregister(ws *websocket.Conn) {
	h.mu.Lock()
	delete(h.clients, ws)
	h.mu.Unlock()
}

// Broadcast sends a message to all connected WebSocket clients.
func (h *Hub) Broadcast(msg []byte) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	for conn := range h.clients {
		if _, err := conn.Write(msg); err != nil {
			h.logger.Error("websocket write error", "error", err)
		}
	}
}

// ClientCount returns the number of connected clients.
func (h *Hub) ClientCount() int {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return len(h.clients)
}

func (s *Server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
	handler := websocket.Handler(func(ws *websocket.Conn) {
		s.hub.Register(ws)
		defer s.hub.Unregister(ws)

		// Keep connection alive until client disconnects.
		buf := make([]byte, 1024)
		for {
			if _, err := ws.Read(buf); err != nil {
				break
			}
		}
	})
	handler.ServeHTTP(w, r)
}