-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgorilla_connection.go
120 lines (95 loc) · 2.53 KB
/
gorilla_connection.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
package wspubsub
import (
"net"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
var _ WebsocketConnection = (*GorillaConnection)(nil)
// GorillaConnection is an implementation of WebsocketConnection.
type GorillaConnection struct {
conn *websocket.Conn
logger Logger
maxMessageSize int64
readTimeout time.Duration
writeTimout time.Duration
IsDebug bool
DebugFuncTimeLimit time.Duration
}
// Read reads a message from WebSocket connection.
func (c *GorillaConnection) Read() (Message, error) {
err := c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
if err != nil {
return Message{}, errors.WithStack(c.handleError(err))
}
messageType, bytes, err := c.conn.ReadMessage()
if err != nil {
return Message{}, errors.WithStack(c.handleError(err))
}
message := Message{
Type: MessageType(messageType),
Payload: bytes,
}
return message, nil
}
// Write writes a message to WebSocket connection.
func (c *GorillaConnection) Write(message Message) error {
if c.IsDebug {
now := time.Now()
defer func() {
end := time.Since(now)
if end > c.DebugFuncTimeLimit {
c.logger.Warnf("wspubsub.gorilla_connection.write: took=%s", end)
}
}()
}
err := c.conn.SetWriteDeadline(time.Now().Add(c.writeTimout))
if err != nil {
return errors.WithStack(c.handleError(err))
}
err = c.conn.WriteMessage(int(message.Type), message.Payload)
if err != nil {
return errors.WithStack(c.handleError(err))
}
return nil
}
// Close closes a WebSocket connection.
func (c *GorillaConnection) Close() error {
if c.IsDebug {
now := time.Now()
defer func() {
end := time.Since(now)
if end > c.DebugFuncTimeLimit {
c.logger.Warnf("wspubsub.gorilla_connection.close: took=%s", end)
}
}()
}
err := c.conn.Close()
if err != nil {
return errors.WithStack(c.handleError(err))
}
return nil
}
func (c *GorillaConnection) handleError(err error) error {
if err == nil {
return nil
}
if _, ok := err.(*websocket.CloseError); ok {
closeErr := NewConnectionClosedError(err)
return errors.WithStack(closeErr)
}
if err == websocket.ErrCloseSent {
closeErr := NewConnectionClosedError(err)
return errors.WithStack(closeErr)
}
if strings.Contains(err.Error(), "use of closed network connection") {
closeErr := NewConnectionClosedError(err)
return errors.WithStack(closeErr)
}
if _, ok := err.(*net.OpError); ok {
closeErr := NewConnectionClosedError(err)
return errors.WithStack(closeErr)
}
return errors.WithStack(err)
}