-
Notifications
You must be signed in to change notification settings - Fork 11
/
rhpsessions.go
45 lines (38 loc) · 987 Bytes
/
rhpsessions.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
package api
import (
"context"
"encoding/json"
"go.sia.tech/hostd/rhp"
"go.sia.tech/jape"
"go.uber.org/zap"
"nhooyr.io/websocket"
)
type rhpSessionSubscriber struct {
conn *websocket.Conn
}
func (rs *rhpSessionSubscriber) ReceiveSessionEvent(event rhp.SessionEvent) {
buf, err := json.Marshal(event)
if err != nil {
return
}
rs.conn.Write(context.Background(), websocket.MessageText, buf)
}
func (a *api) handleGETSessions(c jape.Context) {
a.writeResponse(c, SessionResp(a.sessions.Active()))
}
func (a *api) handleGETSessionsSubscribe(c jape.Context) {
wsc, err := websocket.Accept(c.ResponseWriter, c.Request, &websocket.AcceptOptions{
OriginPatterns: []string{"*"},
})
if err != nil {
a.log.Warn("failed to accept websocket connection", zap.Error(err))
return
}
defer wsc.Close(websocket.StatusNormalClosure, "")
// subscribe the websocket conn
sub := &rhpSessionSubscriber{
conn: wsc,
}
a.sessions.Subscribe(sub)
a.sessions.Unsubscribe(sub)
}