-
Notifications
You must be signed in to change notification settings - Fork 0
/
connector.go
84 lines (65 loc) · 1.5 KB
/
connector.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
package connect
import (
"context"
"fmt"
"net/http"
"net/url"
"sync"
"time"
"github.com/ivan1993spb/snake-bot/internal/config"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
const (
websocketInsecureScheme = "ws"
websocketSecureScheme = "wss"
)
const gameWebsocketPathFormat = "/ws/games/%d"
const handshakeTimeout = 45 * time.Second
const headerClientName = "X-Snake-Client"
type Connector struct {
address string
wss bool
dialer *websocket.Dialer
http.Header
}
func NewConnector(cfg config.Target, clientName string) *Connector {
c := &Connector{
address: cfg.Address,
wss: cfg.WSS,
}
c.dialer = &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: handshakeTimeout,
}
c.Header = http.Header{}
c.Header.Add(headerClientName, clientName)
return c
}
func getGameWebSocketPath(gameId int) string {
return fmt.Sprintf(gameWebsocketPathFormat, gameId)
}
func (c *Connector) getGameWebWocketURL(gameId int) *url.URL {
u := &url.URL{
Host: c.address,
Scheme: websocketInsecureScheme,
}
if c.wss {
u.Scheme = websocketSecureScheme
}
u.Path = getGameWebSocketPath(gameId)
return u
}
func (c *Connector) Connect(ctx context.Context, gameId int) (Connection, error) {
u := c.getGameWebWocketURL(gameId)
ws, resp, err := c.dialer.DialContext(ctx, u.String(), c.Header)
if err != nil {
return nil, errors.Wrap(err, "cannot connect")
}
conn := &connection{
conn: ws,
resp: resp,
mux: &sync.Mutex{},
}
return conn, nil
}