-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_dialer.go
58 lines (53 loc) · 1.3 KB
/
ws_dialer.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
package transport
import (
"context"
"net"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
"github.com/josexy/mini-ss/connection"
)
// WsProxyFuncForTesting this global function used for testing
var WsProxyFuncForTesting func(req *http.Request) (*url.URL, error)
type wsDialer struct {
tcpDialer
opts *WsOptions
}
func (d *wsDialer) Dial(ctx context.Context, addr string) (net.Conn, error) {
scheme := "ws"
tlsConfig, err := d.opts.GetClientTlsConfig()
if err != nil {
return nil, err
}
if tlsConfig != nil {
scheme = "wss"
}
urls := url.URL{
Scheme: scheme,
Host: addr,
Path: d.opts.Path,
}
dialer := &websocket.Dialer{
NetDialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.tcpDialer.Dial(ctx, addr)
},
Proxy: WsProxyFuncForTesting,
ReadBufferSize: d.opts.RevBuffer,
WriteBufferSize: d.opts.SndBuffer,
EnableCompression: d.opts.Compress,
TLSClientConfig: tlsConfig,
HandshakeTimeout: 30 * time.Second,
}
header := http.Header{}
header.Set("Host", d.opts.Host)
if d.opts.UserAgent != "" {
header.Add("User-Agent", d.opts.UserAgent)
}
conn, resp, err := dialer.Dial(urls.String(), header)
if err != nil {
return nil, err
}
resp.Body.Close()
return connection.NewWebsocketConn(conn), nil
}