-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_handler.go
260 lines (193 loc) · 6.64 KB
/
websocket_handler.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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"log"
"net/http"
"time"
)
var wsUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var connections []*websocket.Conn
var backendConnections []*websocket.Conn
type WebsocketHandler struct {
backendKey string
}
type Response struct {
Error bool `json:"error"`
Message *string `json:"message"`
Method *string `json:"method"`
Data *map[string]interface{} `json:"data"`
}
func NewResponse(error bool, message string, method string, data *map[string]interface{}) *Response {
response := new(Response)
response.Error = error
if len(message) > 0 {
response.Message = &message
}
if len(method) > 0 {
response.Method = &method
}
response.Data = data
return response
}
func NewWebsocketHandler() *WebsocketHandler {
handler := new(WebsocketHandler)
handler.backendKey = uuid.New().String()
return handler
}
func (websocketHandler WebsocketHandler) handler(c *gin.Context) {
conn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("failed to set websocket upgrade: %+v\n", err)
return
}
connections = append(connections, conn)
websocketHandler.log("new connection", 200, time.Now(), c.ClientIP())
for {
t, bytes, err := conn.ReadMessage()
since := time.Now()
if t != websocket.TextMessage {
err = websocketHandler.sendResponse(conn, NewResponse(true, "message must be textmessage", "", nil))
websocketHandler.log("", 400, since, c.ClientIP())
return
}
var body map[string]interface{}
err = json.Unmarshal(bytes, &body)
if err != nil {
err = websocketHandler.sendResponse(conn, NewResponse(true, "could not parse json body", "", nil))
websocketHandler.log("", 400, since, c.ClientIP())
return
}
method, err := websocketHandler.methodHandler(conn, body)
status := 0
if err == nil && len(method) > 0 {
status = 200
} else {
status = 400
}
websocketHandler.log(method, status, since, c.ClientIP())
if err != nil {
connections = remove(connections, conn)
backendConnections = remove(backendConnections, conn)
err = conn.Close()
if err != nil {
log.Println(err.Error())
}
return
}
}
}
func (websocketHandler WebsocketHandler) sendResponse(conn *websocket.Conn, response *Response) error {
dataBytes, err := json.Marshal(response)
if err != nil {
return err
}
return conn.WriteMessage(websocket.TextMessage, dataBytes)
}
func (websocketHandler WebsocketHandler) methodHandler(conn *websocket.Conn, body map[string]interface{}) (string, error) {
if body["method"] == nil {
return "", websocketHandler.sendResponse(conn, NewResponse(true, "no method in json body", "", nil))
}
method, s := body["method"].(string)
if !s {
return "", websocketHandler.sendResponse(conn, NewResponse(true, "method is not a string", "", nil))
}
switch method {
case "login":
return method, websocketHandler.loginMethod(conn, body)
case "broadcast":
return method, websocketHandler.broadcastMethod(conn, body)
case "count":
return method, websocketHandler.countMethod(conn)
}
return method, websocketHandler.sendResponse(conn, NewResponse(true, "could not find method", method, nil))
}
func (websocketHandler WebsocketHandler) loginMethod(conn *websocket.Conn, body map[string]interface{}) error {
if body["key"] == nil {
return websocketHandler.sendResponse(conn, NewResponse(true, "no key in json body", "login", nil))
}
key, s := body["key"].(string)
if !s {
return websocketHandler.sendResponse(conn, NewResponse(true, "key is not a string", "login", nil))
}
if key != websocketHandler.backendKey {
return websocketHandler.sendResponse(conn, NewResponse(true, "key is not correct", "login", nil))
}
connections = remove(connections, conn)
backendConnections = append(backendConnections, conn)
return websocketHandler.sendResponse(conn, NewResponse(false, "backend logged in", "login", nil))
}
func (websocketHandler WebsocketHandler) broadcastMethod(conn *websocket.Conn, body map[string]interface{}) error {
connectionIsBackend := websocketHandler.connectionIsBackend(conn)
if !connectionIsBackend {
return websocketHandler.sendResponse(conn, NewResponse(true, "only backend is allowed to broadcast", "broadcast", nil))
}
if body["data"] == nil {
return websocketHandler.sendResponse(conn, NewResponse(true, "no data in json body", "broadcast", nil))
}
data, s := body["data"].(map[string]interface{})
if !s {
return websocketHandler.sendResponse(conn, NewResponse(true, "data is not json object", "broadcast", nil))
}
dataBytes, err := json.Marshal(data)
if err != nil {
return websocketHandler.sendResponse(conn, NewResponse(true, "failed to stringify data json", "broadcast", nil))
}
for _, c := range connections {
err = c.WriteMessage(websocket.TextMessage, dataBytes)
if err != nil {
connections = remove(connections, c)
}
err = nil
}
return websocketHandler.sendResponse(conn, NewResponse(false, "broadcasted message", "broadcast", nil))
}
func (websocketHandler WebsocketHandler) countMethod(conn *websocket.Conn) error {
connectionIsBackend := websocketHandler.connectionIsBackend(conn)
if !connectionIsBackend {
return websocketHandler.sendResponse(conn, NewResponse(true, "only backend is allowed to count", "count", nil))
}
response := make(map[string]interface{})
response["connectionCount"] = len(connections)
response["backendConnectionCount"] = len(backendConnections)
return websocketHandler.sendResponse(conn, NewResponse(false, "connections count", "count", &response))
}
func (websocketHandler WebsocketHandler) log(method string, statusCode int, since time.Time, clientIp string) {
param := new(gin.LogFormatterParams)
param.Path = method
param.Method = http.MethodGet
param.ClientIP = clientIp
param.Latency = time.Since(since)
param.StatusCode = statusCode
param.TimeStamp = time.Now()
statusColor := param.StatusCodeColor()
methodColor := param.MethodColor()
resetColor := param.ResetColor()
param.Method = "Websocket"
if param.Latency > time.Minute {
param.Latency = param.Latency.Truncate(time.Second)
}
log.Println(fmt.Sprintf("[GIN-WS] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
param.TimeStamp.Format("2006/01/02 - 15:04:05"),
statusColor, param.StatusCode, resetColor,
param.Latency,
param.ClientIP,
methodColor, param.Method, resetColor,
param.Path,
param.ErrorMessage,
))
}
func (websocketHandler WebsocketHandler) connectionIsBackend(conn *websocket.Conn) bool {
for _, c := range backendConnections {
if c == conn {
return true
}
}
return false
}