websocket.go
11.5 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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package httpexpect
import (
"encoding/json"
"time"
"github.com/gorilla/websocket"
)
const noDuration = time.Duration(0)
var infiniteTime = time.Time{}
// Websocket provides methods to read from, write into and close WebSocket
// connection.
type Websocket struct {
config Config
chain chain
conn *websocket.Conn
readTimeout time.Duration
writeTimeout time.Duration
isClosed bool
}
// NewWebsocket returns a new Websocket given a Config with Reporter and
// Printers, and websocket.Conn to be inspected and handled.
func NewWebsocket(config Config, conn *websocket.Conn) *Websocket {
return makeWebsocket(config, makeChain(config.Reporter), conn)
}
func makeWebsocket(config Config, chain chain, conn *websocket.Conn) *Websocket {
return &Websocket{
config: config,
chain: chain,
conn: conn,
}
}
// Raw returns underlying websocket.Conn object.
// This is the value originally passed to NewConnection.
func (c *Websocket) Raw() *websocket.Conn {
return c.conn
}
// WithReadTimeout sets timeout duration for WebSocket connection reads.
//
// By default no timeout is used.
func (c *Websocket) WithReadTimeout(timeout time.Duration) *Websocket {
c.readTimeout = timeout
return c
}
// WithoutReadTimeout removes timeout for WebSocket connection reads.
func (c *Websocket) WithoutReadTimeout() *Websocket {
c.readTimeout = noDuration
return c
}
// WithWriteTimeout sets timeout duration for WebSocket connection writes.
//
// By default no timeout is used.
func (c *Websocket) WithWriteTimeout(timeout time.Duration) *Websocket {
c.writeTimeout = timeout
return c
}
// WithoutWriteTimeout removes timeout for WebSocket connection writes.
//
// If not used then DefaultWebsocketTimeout will be used.
func (c *Websocket) WithoutWriteTimeout() *Websocket {
c.writeTimeout = noDuration
return c
}
// Subprotocol returns a new String object that may be used to inspect
// negotiated protocol for the connection.
func (c *Websocket) Subprotocol() *String {
s := &String{chain: c.chain}
if c.conn != nil {
s.value = c.conn.Subprotocol()
}
return s
}
// Expect reads next message from WebSocket connection and
// returns a new WebsocketMessage object to inspect received message.
//
// Example:
// msg := conn.Expect()
// msg.JSON().Object().ValueEqual("message", "hi")
func (c *Websocket) Expect() *WebsocketMessage {
switch {
case c.chain.failed():
return makeWebsocketMessage(c.chain)
case c.conn == nil:
c.chain.fail("\nunexpected read from failed WebSocket connection")
return makeWebsocketMessage(c.chain)
case c.isClosed:
c.chain.fail("\nunexpected read from closed WebSocket connection")
return makeWebsocketMessage(c.chain)
case !c.setReadDeadline():
return makeWebsocketMessage(c.chain)
}
var err error
m := makeWebsocketMessage(c.chain)
m.typ, m.content, err = c.conn.ReadMessage()
if err != nil {
if cls, ok := err.(*websocket.CloseError); ok {
m.typ = websocket.CloseMessage
m.closeCode = cls.Code
m.content = []byte(cls.Text)
c.printRead(m.typ, m.content, m.closeCode)
} else {
c.chain.fail(
"\nexpected read WebSocket connection, "+
"but got failure: %s", err.Error())
return makeWebsocketMessage(c.chain)
}
} else {
c.printRead(m.typ, m.content, m.closeCode)
}
return m
}
func (c *Websocket) setReadDeadline() bool {
deadline := infiniteTime
if c.readTimeout != noDuration {
deadline = time.Now().Add(c.readTimeout)
}
if err := c.conn.SetReadDeadline(deadline); err != nil {
c.chain.fail(
"\nunexpected failure when setting "+
"read WebSocket connection deadline: %s", err.Error())
return false
}
return true
}
func (c *Websocket) printRead(typ int, content []byte, closeCode int) {
for _, printer := range c.config.Printers {
if p, ok := printer.(WebsocketPrinter); ok {
p.WebsocketRead(typ, content, closeCode)
}
}
}
// Disconnect closes the underlying WebSocket connection without sending or
// waiting for a close message.
//
// It's okay to call this function multiple times.
//
// It's recommended to always call this function after connection usage is over
// to ensure that no resource leaks will happen.
//
// Example:
// conn := resp.Connection()
// defer conn.Disconnect()
func (c *Websocket) Disconnect() *Websocket {
if c.conn == nil || c.isClosed {
return c
}
c.isClosed = true
if err := c.conn.Close(); err != nil {
c.chain.fail("close error when disconnecting webcoket: " + err.Error())
}
return c
}
// Close cleanly closes the underlying WebSocket connection
// by sending an empty close message and then waiting (with timeout)
// for the server to close the connection.
//
// WebSocket close code may be optionally specified.
// If not, then "1000 - Normal Closure" will be used.
//
// WebSocket close codes are defined in RFC 6455, section 11.7.
// See also https://godoc.org/github.com/gorilla/websocket#pkg-constants
//
// It's okay to call this function multiple times.
//
// Example:
// conn := resp.Connection()
// conn.Close(websocket.CloseUnsupportedData)
func (c *Websocket) Close(code ...int) *Websocket {
switch {
case c.checkUnusable("Close"):
return c
case len(code) > 1:
c.chain.fail("\nunexpected multiple code arguments passed to Close")
return c
}
return c.CloseWithBytes(nil, code...)
}
// CloseWithBytes cleanly closes the underlying WebSocket connection
// by sending given slice of bytes as a close message and then waiting
// (with timeout) for the server to close the connection.
//
// WebSocket close code may be optionally specified.
// If not, then "1000 - Normal Closure" will be used.
//
// WebSocket close codes are defined in RFC 6455, section 11.7.
// See also https://godoc.org/github.com/gorilla/websocket#pkg-constants
//
// It's okay to call this function multiple times.
//
// Example:
// conn := resp.Connection()
// conn.CloseWithBytes([]byte("bye!"), websocket.CloseGoingAway)
func (c *Websocket) CloseWithBytes(b []byte, code ...int) *Websocket {
switch {
case c.checkUnusable("CloseWithBytes"):
return c
case len(code) > 1:
c.chain.fail(
"\nunexpected multiple code arguments passed to CloseWithBytes")
return c
}
c.WriteMessage(websocket.CloseMessage, b, code...)
return c
}
// CloseWithJSON cleanly closes the underlying WebSocket connection
// by sending given object (marshaled using json.Marshal()) as a close message
// and then waiting (with timeout) for the server to close the connection.
//
// WebSocket close code may be optionally specified.
// If not, then "1000 - Normal Closure" will be used.
//
// WebSocket close codes are defined in RFC 6455, section 11.7.
// See also https://godoc.org/github.com/gorilla/websocket#pkg-constants
//
// It's okay to call this function multiple times.
//
// Example:
// type MyJSON struct {
// Foo int `json:"foo"`
// }
//
// conn := resp.Connection()
// conn.CloseWithJSON(MyJSON{Foo: 123}, websocket.CloseUnsupportedData)
func (c *Websocket) CloseWithJSON(
object interface{}, code ...int,
) *Websocket {
switch {
case c.checkUnusable("CloseWithJSON"):
return c
case len(code) > 1:
c.chain.fail(
"\nunexpected multiple code arguments passed to CloseWithJSON")
return c
}
b, err := json.Marshal(object)
if err != nil {
c.chain.fail(err.Error())
return c
}
return c.CloseWithBytes(b, code...)
}
// CloseWithText cleanly closes the underlying WebSocket connection
// by sending given text as a close message and then waiting (with timeout)
// for the server to close the connection.
//
// WebSocket close code may be optionally specified.
// If not, then "1000 - Normal Closure" will be used.
//
// WebSocket close codes are defined in RFC 6455, section 11.7.
// See also https://godoc.org/github.com/gorilla/websocket#pkg-constants
//
// It's okay to call this function multiple times.
//
// Example:
// conn := resp.Connection()
// conn.CloseWithText("bye!")
func (c *Websocket) CloseWithText(s string, code ...int) *Websocket {
switch {
case c.checkUnusable("CloseWithText"):
return c
case len(code) > 1:
c.chain.fail(
"\nunexpected multiple code arguments passed to CloseWithText")
return c
}
return c.CloseWithBytes([]byte(s), code...)
}
// WriteMessage writes to the underlying WebSocket connection a message
// of given type with given content.
// Additionally, WebSocket close code may be specified for close messages.
//
// WebSocket message types are defined in RFC 6455, section 11.8.
// See also https://godoc.org/github.com/gorilla/websocket#pkg-constants
//
// WebSocket close codes are defined in RFC 6455, section 11.7.
// See also https://godoc.org/github.com/gorilla/websocket#pkg-constants
//
// Example:
// conn := resp.Connection()
// conn.WriteMessage(websocket.CloseMessage, []byte("Namárië..."))
func (c *Websocket) WriteMessage(
typ int, content []byte, closeCode ...int,
) *Websocket {
if c.checkUnusable("WriteMessage") {
return c
}
switch typ {
case websocket.TextMessage, websocket.BinaryMessage:
c.printWrite(typ, content, 0)
case websocket.CloseMessage:
if len(closeCode) > 1 {
c.chain.fail("\nunexpected multiple closeCode arguments " +
"passed to WriteMessage")
return c
}
code := websocket.CloseNormalClosure
if len(closeCode) > 0 {
code = closeCode[0]
}
c.printWrite(typ, content, code)
content = websocket.FormatCloseMessage(code, string(content))
default:
c.chain.fail("\nunexpected WebSocket message type '%s' "+
"passed to WriteMessage", wsMessageTypeName(typ))
return c
}
if !c.setWriteDeadline() {
return c
}
if err := c.conn.WriteMessage(typ, content); err != nil {
c.chain.fail(
"\nexpected write into WebSocket connection, "+
"but got failure: %s", err.Error())
}
return c
}
// WriteBytesBinary is a shorthand for c.WriteMessage(websocket.BinaryMessage, b).
func (c *Websocket) WriteBytesBinary(b []byte) *Websocket {
if c.checkUnusable("WriteBytesBinary") {
return c
}
return c.WriteMessage(websocket.BinaryMessage, b)
}
// WriteBytesText is a shorthand for c.WriteMessage(websocket.TextMessage, b).
func (c *Websocket) WriteBytesText(b []byte) *Websocket {
if c.checkUnusable("WriteBytesText") {
return c
}
return c.WriteMessage(websocket.TextMessage, b)
}
// WriteText is a shorthand for
// c.WriteMessage(websocket.TextMessage, []byte(s)).
func (c *Websocket) WriteText(s string) *Websocket {
if c.checkUnusable("WriteText") {
return c
}
return c.WriteMessage(websocket.TextMessage, []byte(s))
}
// WriteJSON writes to the underlying WebSocket connection given object,
// marshaled using json.Marshal().
func (c *Websocket) WriteJSON(object interface{}) *Websocket {
if c.checkUnusable("WriteJSON") {
return c
}
b, err := json.Marshal(object)
if err != nil {
c.chain.fail(err.Error())
return c
}
return c.WriteMessage(websocket.TextMessage, b)
}
func (c *Websocket) checkUnusable(where string) bool {
switch {
case c.chain.failed():
return true
case c.conn == nil:
c.chain.fail("\nunexpected %s call for failed WebSocket connection",
where)
return true
case c.isClosed:
c.chain.fail("\nunexpected %s call for closed WebSocket connection",
where)
return true
}
return false
}
func (c *Websocket) setWriteDeadline() bool {
deadline := infiniteTime
if c.writeTimeout != noDuration {
deadline = time.Now().Add(c.writeTimeout)
}
if err := c.conn.SetWriteDeadline(deadline); err != nil {
c.chain.fail(
"\nunexpected failure when setting "+
"write WebSocket connection deadline: %s", err.Error())
return false
}
return true
}
func (c *Websocket) printWrite(typ int, content []byte, closeCode int) {
for _, printer := range c.config.Printers {
if p, ok := printer.(WebsocketPrinter); ok {
p.WebsocketWrite(typ, content, closeCode)
}
}
}