forked from SecurityBrewery/catalyst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
82 lines (67 loc) · 1.58 KB
/
websocket.go
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
package catalyst
import (
"encoding/json"
"errors"
"net/http"
"sync"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/google/uuid"
"github.com/sarcb/catalyst-sp24/bus"
"github.com/sarcb/catalyst-sp24/generated/api"
)
type websocketBroker struct {
clients map[string]chan []byte
mu sync.Mutex
}
func (wb *websocketBroker) Publish(b []byte) {
for _, channel := range wb.clients {
channel <- b
}
}
func (wb *websocketBroker) CloseSocket(id string) {
wb.mu.Lock()
if channel, ok := wb.clients[id]; ok {
close(channel)
delete(wb.clients, id)
}
wb.mu.Unlock()
}
func (wb *websocketBroker) NewWebsocket() (string, chan []byte) {
id := uuid.New().String()
channel := make(chan []byte, 10)
wb.mu.Lock()
wb.clients[id] = channel
wb.mu.Unlock()
return id, channel
}
func handleWebSocket(catalystBus *bus.Bus) http.HandlerFunc {
broker := websocketBroker{clients: map[string]chan []byte{}}
// send all messages from bus to websocket
catalystBus.DatabaseChannel.Subscribe(func(msg *bus.DatabaseUpdateMsg) {
b, err := json.Marshal(map[string]any{
"action": "update",
"ids": msg.IDs,
})
if err != nil {
return
}
broker.Publish(b)
})
return func(w http.ResponseWriter, r *http.Request) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
if err != nil {
api.JSONError(w, errors.New("upgrade failed"))
return
}
go func() {
defer conn.Close()
id, messages := broker.NewWebsocket()
for msg := range messages {
if err := wsutil.WriteServerMessage(conn, ws.OpText, msg); err != nil {
broker.CloseSocket(id)
}
}
}()
}
}