-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
61 lines (55 loc) · 1.39 KB
/
client.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
package engineio
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"github.com/gorilla/websocket"
"github.com/mushroomsir/engine.io/transports"
)
// Options ...
type Options struct {
// TLSClientConfig specifies the TLS configuration to use with tls.Client.
// If nil, the default configuration is used.
TLSClientConfig *tls.Config
LocalAddr string
RequestHeader http.Header
}
// NewClient ...
func NewClient(urlStr string, opts ...*Options) (client *transports.Client, err error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
query := u.Query()
query.Set("transport", "websocket")
query.Set("EIO", "3")
u.RawQuery = query.Encode()
dialer := &websocket.Dialer{}
var header http.Header
if len(opts) > 0 {
op := opts[0]
if op.TLSClientConfig != nil {
dialer.TLSClientConfig = op.TLSClientConfig
}
if len(op.LocalAddr) < 1 {
dialer.NetDial = func(network, addr string) (net.Conn, error) {
localAddr, err := net.ResolveTCPAddr(network, op.LocalAddr)
if err != nil {
panic(err)
}
netDialer := &net.Dialer{LocalAddr: localAddr}
return netDialer.Dial(network, addr)
}
}
if len(op.RequestHeader) > 0 {
header = op.RequestHeader
}
}
conn, _, err := dialer.Dial(u.String(), header)
if err != nil {
return
}
client = transports.NewWebSocket(conn)
return
}