-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
99 lines (77 loc) · 1.98 KB
/
writer.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
package socketify
import (
"fmt"
"github.com/gorilla/websocket"
"time"
)
type writer struct {
ch chan messageType
logger Logger
}
func newWriter(ch chan messageType, logger Logger) *writer {
w := &writer{ch: ch, logger: logger}
return w
}
func (w *writer) WriteUpdate(updateType string, data interface{}) (err error) {
jm := newJSONMessage(serverUpdate{
Type: updateType,
Data: data,
})
w.ch <- jm
return <-jm.err
}
func (w *writer) WriteRawUpdate(data interface{}) (err error) {
jm := newJSONMessage(data)
w.ch <- jm
return <-jm.err
}
func (w *writer) WriteBinaryBytes(data []byte) (err error) {
jm := newBinaryMessage(data)
w.ch <- jm
return <-jm.err
}
func (w *writer) WriteBinaryText(data []byte) (err error) {
jm := newBinaryTextMessage(data)
w.ch <- jm
return <-jm.err
}
func (w *writer) WriteText(data string) (err error) {
jm := newTextMessage(data)
w.ch <- jm
return <-jm.err
}
func (w *writer) processWriter(ws *websocket.Conn) {
for update := range w.ch {
data, err := update.Data()
if err != nil {
go func(update messageType, err error) {
update.Err() <- err
}(update, err)
w.logger.Error("Error getting message data", err, fmt.Sprintf("update: %+v . RemoteAddr: %s", update, ws.RemoteAddr().String()))
continue
}
err = ws.WriteMessage(update.Type(), data)
if err != nil {
w.logger.Error("Error writing JSON", err, fmt.Sprintf("update: %+v . RemoteAddr: %s", update, ws.RemoteAddr().String()))
}
go func(update messageType, err error) {
update.Err() <- err
}(update, err)
}
}
func (c *Connection) WriteInternalUpdate(update []byte) {
c.internalUpdates <- update
// TODO: Decide to move this to goroutine or not, because people might forget to do so in their application leading \
// to a deadlock
}
func (c *Connection) ping() {
if c.keepAlive != 0 {
ticker := time.NewTicker(c.keepAlive)
for range ticker.C {
err := c.ws.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return
}
}
}
}