-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.go
More file actions
177 lines (156 loc) · 3.99 KB
/
websocket.go
File metadata and controls
177 lines (156 loc) · 3.99 KB
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
// Simple tools for nhooyr websockets with intuitive API (in golang)
package wshelper
import (
"bytes"
"context"
"encoding/json"
"errors"
"github.com/segmentio/ksuid"
"github.com/unxcepted/websocket"
"io"
"net/http"
"reflect"
"strings"
)
var (
Accept = func(w http.ResponseWriter, r *http.Request, opts *websocket.AcceptOptions) (*Connection, error) {
conn, err := websocket.Accept(w, r, opts)
if err != nil {
return nil, err
}
return NewConnection(conn), nil
}
Dial = func(ctx context.Context, u string, opts *websocket.DialOptions) (*Connection, error) {
conn, _, err := websocket.Dial(ctx, u, opts)
if err != nil {
return nil, err
}
return NewConnection(conn), nil
}
)
var (
EmptyCloseHandler = CloseHandler(func(connection *Connection, code websocket.StatusCode, reason string) {})
EmptyErrorHandler = ErrorHandler(func(connection *Connection, err error) {})
)
type CloseHandler func(conn *Connection, code websocket.StatusCode, reason string)
type ErrorHandler func(conn *Connection, err error)
type MessageHandler func(conn *Connection, mtype websocket.MessageType, data Payload)
type MessageBufferHandler func(conn *Connection, mtype websocket.MessageType, data *bytes.Buffer)
type MessageReaderHandler func(conn *Connection, mtype websocket.MessageType, data io.Reader)
type Payload []byte
func (p Payload) Into(v interface{}) error {
if reflect.ValueOf(v).Kind() != reflect.Ptr {
return errors.New("A destination must be a pointer")
}
return json.Unmarshal(p, v)
}
type Connection struct {
onClose CloseHandler
onError ErrorHandler
ws *websocket.Conn
uuid string
closed bool
handler interface{}
rawData *bytes.Buffer
}
func (c *Connection) UUID() string {
return c.uuid
}
func (c *Connection) Close(status websocket.StatusCode, reason string) error {
if c.closed == true {
return nil
}
if err := c.WS().Close(status, reason); err != nil {
return err
}
c.closed = true
return nil
}
func (c *Connection) WS() *websocket.Conn {
return c.ws
}
func (c *Connection) WriteJSON(ctx context.Context, v interface{}) error {
w, err := c.ws.Writer(ctx, websocket.MessageText)
if err != nil {
return err
}
// instead of json.Marshal it will reuse buffers, as we write directly to Writer
err = json.NewEncoder(w).Encode(v)
if err != nil {
return err
}
return w.Close()
}
func (c *Connection) Write(ctx context.Context, typ websocket.MessageType, data []byte) error {
return c.ws.Write(ctx, typ, data)
}
func (c *Connection) OnClose(h CloseHandler) {
c.onClose = h
}
func (c *Connection) OnError(h ErrorHandler) {
c.onError = h
}
func (c *Connection) OnMessage(h MessageHandler) {
c.handler = h
}
func (c *Connection) OnMessageBuffer(h MessageBufferHandler) {
c.handler = h
}
func (c *Connection) OnMessageReader(h MessageReaderHandler) {
c.handler = h
}
func (c *Connection) loop() {
for {
c.rawData.Reset()
if c.closed {
return
}
t, data, err := c.ws.Reader(context.Background())
if err != nil {
var closeErr websocket.CloseError
if errors.As(err, &closeErr) && c.onClose != nil {
c.onClose(c, closeErr.Code, closeErr.Reason)
c.closed = true
break
}
if strings.Contains(err.Error(), "failed to read frame header: EOF") {
if c.onClose != nil {
c.onClose(c, websocket.StatusAbnormalClosure, "the connection was suddenly closed")
}
c.closed = true
break
}
if c.onError != nil {
c.onError(c, err)
}
_ = c.Close(websocket.StatusAbnormalClosure, "-")
break
}
switch h := c.handler.(type) {
case MessageHandler:
_, err = c.rawData.ReadFrom(data)
if err == nil {
h(c, t, c.rawData.Bytes())
}
case MessageBufferHandler:
_, err = c.rawData.ReadFrom(data)
if err == nil {
h(c, t, c.rawData)
}
case MessageReaderHandler:
h(c, t, data)
}
}
}
func NewConnection(conn *websocket.Conn) *Connection {
c := &Connection{
ws: conn,
uuid: ksuid.New().String(),
onClose: nil,
onError: nil,
handler: nil,
rawData: new(bytes.Buffer),
}
go c.loop()
return c
}