-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgorilla_upgrader.go
73 lines (60 loc) · 2.15 KB
/
gorilla_upgrader.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
package wspubsub
import (
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
var _ WebsocketConnectionUpgrader = (*GorillaConnectionUpgrader)(nil)
// GorillaConnectionUpgrader is an implementation of WebsocketConnectionUpgrader.
type GorillaConnectionUpgrader struct {
options GorillaConnectionUpgraderOptions
logger Logger
upgrader *websocket.Upgrader
}
// GorillaConnectionUpgrader upgrades HTTP connection to the WebSocket connection.
func (u *GorillaConnectionUpgrader) Upgrade(w http.ResponseWriter, r *http.Request) (WebsocketConnection, error) {
if u.options.IsDebug {
now := time.Now()
defer func() {
end := time.Since(now)
if end > u.options.DebugFuncTimeLimit {
u.logger.Warnf("gorilla.connection_upgrader.upgrader: took=%s", end)
}
}()
}
connection, err := u.upgrader.Upgrade(w, r, nil)
if err != nil {
return nil, errors.WithStack(err)
}
connection.SetReadLimit(u.options.MaxMessageSize)
err = connection.SetReadDeadline(time.Now().Add(u.options.ReadTimout))
if err != nil {
return nil, errors.WithStack(err)
}
connection.SetPongHandler(func(string) error {
return connection.SetReadDeadline(time.Now().Add(u.options.ReadTimout))
})
gorillaConnection := &GorillaConnection{
conn: connection,
logger: u.logger,
maxMessageSize: u.options.MaxMessageSize,
readTimeout: u.options.ReadTimout,
writeTimout: u.options.WriteTimout,
IsDebug: u.options.IsDebug,
DebugFuncTimeLimit: u.options.DebugFuncTimeLimit,
}
return gorillaConnection, nil
}
// NewGorillaConnectionUpgrader initializes a new GorillaConnectionUpgrader.
func NewGorillaConnectionUpgrader(options GorillaConnectionUpgraderOptions, logger Logger) *GorillaConnectionUpgrader {
upgrader := &websocket.Upgrader{
HandshakeTimeout: options.HandshakeTimeout,
ReadBufferSize: options.ReadBufferSize,
WriteBufferSize: options.WriteBufferSize,
Subprotocols: options.Subprotocols,
CheckOrigin: options.CheckOrigin,
EnableCompression: options.EnableCompression,
}
return &GorillaConnectionUpgrader{options: options, logger: logger, upgrader: upgrader}
}