-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
93 lines (84 loc) · 1.75 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
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
const (
MAX_MSG_SIZE = 5000
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 2048,
WriteBufferSize: 2048,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type WebSocket struct {
Conn *websocket.Conn
Out chan []byte
In chan []byte
Events map[string]EventHandler
}
func NewWebSocket(w http.ResponseWriter, r *http.Request) (*WebSocket, error) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("[ERROR | SOCKET CONNECT] %v", err)
return nil, err
}
// conn.SetWriteDeadline(time.Now().Add(MSG_TIMEOUT))
ws := &WebSocket{
Conn: conn,
Out: make(chan []byte),
In: make(chan []byte),
Events: make(map[string]EventHandler),
}
go ws.Reader()
go ws.Writer()
return ws, nil
}
func (ws *WebSocket) Reader() {
defer func() {
ws.Conn.Close()
}()
ws.Conn.SetReadLimit(MAX_MSG_SIZE)
for {
_, message, err := ws.Conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("[ERROR] %v", err)
}
break
}
event, err := NewEventFromRaw(message)
if err != nil {
log.Printf("[ERROR | MSG] %v", err)
} else {
log.Printf("[MSG] %v", event)
}
if action, ok := ws.Events[event.Name]; ok {
action(event)
}
}
}
func (ws *WebSocket) Writer() {
for {
select {
case message, ok := <-ws.Out:
if !ok {
ws.Conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := ws.Conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
w.Close()
}
}
}
func (ws *WebSocket) On(event string, action EventHandler) *WebSocket {
ws.Events[event] = action
return ws
}