/
connector.go
79 lines (59 loc) · 1.37 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
package connect
import (
"context"
"fmt"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/ivan1993spb/snake-bot/internal/config"
)
type Connector struct {
address string
wss bool
dialer *websocket.Dialer
header http.Header
}
const handshakeTimeout = 45 * time.Second
const HeaderClientName = "X-Snake-Client"
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
}
const gameWebsocketPathFormat = "/ws/games/%d"
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: "ws",
}
if c.wss {
u.Scheme = "wss"
}
u.Path = getGameWebSocketPath(gameId)
return u
}
func (c *Connector) Connect(ctx context.Context, gameId int) (Connection, error) {
u := c.getGameWebWocketURL(gameId).String()
ws, resp, err := c.dialer.DialContext(ctx, u, c.header)
if err != nil {
return nil, errors.Wrap(err, "failed to connect")
}
conn := &connection{
conn: ws,
resp: resp,
}
return conn, nil
}