/
client.go
125 lines (103 loc) · 2.42 KB
/
client.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
package ws
import (
"encoding/json"
"io"
"net"
"sync"
"github.com/bleenco/abstruse/internal/auth"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
// Client defines websocket connection.
// It contains logic of receiving and sending messages.
// That is, there are no active reader or writer. Some other layer
// of the application should call Receive() to read user's
// incoming message.
type Client struct {
io sync.Mutex
conn io.ReadWriteCloser
c net.Conn
data auth.UserClaims
subs []string
}
// Receive reads next message from user's underlying connection.
// It blocks until full message received.
func (c *Client) Receive() (*Message, error) {
msg, err := c.readMessage()
if err != nil {
c.conn.Close()
return nil, err
}
if msg == nil {
// Handled some control message.
return nil, nil
}
return msg, nil
}
// Send sends message to user's underlying connection.
func (c *Client) Send(mtype string, data Object) error {
return c.writeTo(mtype, data)
}
// readRequests reads json-rpc request from connection.
// It takes io mutex.
func (c *Client) readMessage() (*Message, error) {
c.io.Lock()
defer c.io.Unlock()
h, r, err := wsutil.NextReader(c.conn, ws.StateServerSide)
if err != nil {
return nil, err
}
if h.OpCode.IsControl() {
return nil, wsutil.ControlFrameHandler(c.conn, ws.StateServerSide)(h, r)
}
msg := &Message{}
decoder := json.NewDecoder(r)
if err := decoder.Decode(msg); err != nil {
return nil, err
}
return msg, nil
}
func (c *Client) writeTo(mtype string, data Object) error {
return c.write(Message{
Type: mtype,
Data: data,
})
}
func (c *Client) writeErrorTo(data Object) error {
err := &Message{Type: "error", Data: data}
return c.write(err)
}
func (c *Client) write(x interface{}) error {
w := wsutil.NewWriter(c.conn, ws.StateServerSide, ws.OpText)
encoder := json.NewEncoder(w)
if err := encoder.Encode(x); err != nil {
return err
}
return w.Flush()
}
func (c *Client) writeRaw(p []byte) error {
c.io.Lock()
defer c.io.Unlock()
_, err := c.conn.Write(p)
return err
}
func (c *Client) subscribe(sub string) {
if !c.isSubscribed(sub) {
c.subs = append(c.subs, sub)
}
}
func (c *Client) unsubscribe(sub string) {
for i, s := range c.subs {
if s == sub {
c.subs = append(c.subs[:i], c.subs[i+1:]...)
}
}
}
func (c *Client) isSubscribed(data string) bool {
for _, s := range c.subs {
if s == data {
return true
}
}
return false
}