-
Notifications
You must be signed in to change notification settings - Fork 2
/
websocket.go
118 lines (101 loc) · 2.62 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
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
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"github.com/PiotrTopa/js8web/model"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type websocketSession struct {
user string
events chan<- model.WebsocketMessage
}
type websocketSessionContainer struct {
sessions map[string]websocketSession
}
func (o *websocketSessionContainer) init() {
o.sessions = make(map[string]websocketSession)
}
func (o *websocketSessionContainer) register(id string, session websocketSession) error {
if len(id) == 0 {
return errors.New("no session id specified")
}
if _, exists := o.sessions[id]; exists {
return errors.New("session already registered")
}
o.sessions[id] = session
return nil
}
func (o *websocketSessionContainer) deregister(id string) error {
if len(id) == 0 {
return errors.New("no session id specified")
}
if session, exists := o.sessions[id]; exists {
close(session.events)
delete(o.sessions, id)
return nil
}
return errors.New("session with given id has not been rgistered")
}
func (o *websocketSessionContainer) process(messages <-chan model.WebsocketMessage) {
for message := range messages {
for _, session := range o.sessions {
session.events <- message
}
}
}
func websocketHandler(sessionContainer *websocketSessionContainer) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Sugar().Errorw(
"Can not upgrade WebSocket connection",
"request", r,
"error", err,
)
http.Error(w, "cannot upgrade connection", http.StatusUpgradeRequired)
return
}
defer ws.Close()
messages := make(chan model.WebsocketMessage)
sessionId := uuid.New().String()
session := websocketSession{
user: "test",
events: messages,
}
err = sessionContainer.register(
sessionId,
session,
)
if err != nil {
logger.Sugar().Errorw(
"Can not register WebSocket session",
"request", r,
"error", err,
)
http.Error(w, "cannot register connection session", http.StatusUpgradeRequired)
}
defer sessionContainer.deregister(sessionId)
for message := range messages {
messageJson, err := json.Marshal(message)
if err != nil {
logger.Sugar().Errorw(
"Cannot marshall WebSocket message",
"message", message,
"session", session,
)
}
if err := ws.WriteMessage(websocket.TextMessage, messageJson); err != nil {
log.Println(err)
return
}
}
}
}