-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.go
58 lines (44 loc) · 968 Bytes
/
session.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
package main
import (
"time"
. "github.com/google/uuid"
"github.com/gorilla/websocket"
)
type Client struct {
conn *websocket.Conn
broadcast chan *Event
}
func newClient(conn *websocket.Conn) *Client {
return &Client{
conn: conn,
broadcast: make(chan *Event),
}
}
// The Dispatcher; we spawn one for every client
func (c *Client) tx() {
defer c.conn.Close()
for {
event, ok := <-c.broadcast
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
c.conn.WriteJSON(event)
}
}
type SessionManager struct {
sessions map[UUID]*Client
}
func NewSessionManager() *SessionManager {
return &SessionManager{
sessions: make(map[UUID]*Client),
}
}
func (sm *SessionManager) register(sessionID UUID, conn *websocket.Conn) {
sm.sessions[sessionID] = &Client{
conn: conn,
broadcast: make(chan *Event),
}
go sm.sessions[sessionID].tx()
}