-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
185 lines (158 loc) · 4.41 KB
/
server.go
File metadata and controls
185 lines (158 loc) · 4.41 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"context"
"embed"
"encoding/json"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
//go:embed static/index.html
var staticFS embed.FS
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
type Server struct {
port string
imageDir string
cfg *Config
clients map[*websocket.Conn]struct{}
mu sync.RWMutex
done <-chan struct{}
}
func NewServer(port, imageDir string, cfg *Config, done <-chan struct{}) *Server {
return &Server{
port: port,
imageDir: imageDir,
cfg: cfg,
clients: make(map[*websocket.Conn]struct{}),
done: done,
}
}
// HasClients returns true if at least one WebSocket client is connected.
func (s *Server) HasClients() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.clients) > 0
}
// BroadcastSessionImage sends a SessionImage as JSON to all connected WebSocket clients.
func (s *Server) BroadcastSessionImage(si SessionImage) {
data, err := json.Marshal(si)
if err != nil {
log.Printf("json marshal error: %v", err)
return
}
// Snapshot connections under lock, then release before I/O
s.mu.RLock()
conns := make([]*websocket.Conn, 0, len(s.clients))
for conn := range s.clients {
conns = append(conns, conn)
}
s.mu.RUnlock()
for _, conn := range conns {
if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
log.Printf("websocket write error: %v", err)
}
}
}
// Start begins serving HTTP and WebSocket connections. It blocks until
// the done channel is closed, then gracefully shuts down the HTTP server.
func (s *Server) Start() error {
mux := http.NewServeMux()
// Serve index.html
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
data, err := staticFS.ReadFile("static/index.html")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(data)
})
// Serve generated images
mux.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(s.imageDir))))
// WebSocket endpoint
mux.HandleFunc("/ws", s.handleWS)
// Config API endpoints
mux.HandleFunc("/api/config", s.handleConfig)
httpServer := &http.Server{
Addr: ":" + s.port,
Handler: mux,
}
// Shut down the HTTP server when done is closed.
go func() {
<-s.done
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Printf("http server shutdown error: %v", err)
}
}()
log.Printf("server listening on :%s", s.port)
if err := httpServer.ListenAndServe(); err != http.ErrServerClosed {
return err
}
return nil
}
func (s *Server) handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("websocket upgrade error: %v", err)
return
}
s.mu.Lock()
s.clients[conn] = struct{}{}
s.mu.Unlock()
log.Printf("WebSocket client connected (total: %d)", len(s.clients))
// Keep connection alive; remove on close.
defer func() {
s.mu.Lock()
delete(s.clients, conn)
s.mu.Unlock()
conn.Close()
log.Printf("WebSocket client disconnected (total: %d)", len(s.clients))
}()
// Close the connection when done is signaled so ReadMessage unblocks.
go func() {
<-s.done
conn.Close()
}()
for {
if _, _, err := conn.ReadMessage(); err != nil {
break
}
}
}
func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
rc := s.cfg.GetRuntimeConfig()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(rc)
case http.MethodPut:
var rc RuntimeConfig
if err := json.NewDecoder(r.Body).Decode(&rc); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON"})
return
}
if err := s.cfg.SetRuntimeConfig(rc); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
log.Printf("runtime config updated: %+v", rc)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(s.cfg.GetRuntimeConfig())
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}