-
Notifications
You must be signed in to change notification settings - Fork 5
/
websocket.go
84 lines (71 loc) · 1.67 KB
/
websocket.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 gwlb
import (
"context"
"crypto/tls"
"fmt"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"net"
"net/http"
)
func proxyWebsocket(w http.ResponseWriter, r *http.Request, tlsClientConfig *tls.Config) {
up := websocket.Upgrader{CheckOrigin: nil} // TODO: check this field
ctx := r.Context()
port := ctx.Value(http.LocalAddrContextKey).(*net.TCPAddr).Port
if port == 443 {
r.URL.Scheme = "wss"
} else if port == 80 {
r.URL.Scheme = "ws"
}
newHeaders := r.Header.Clone()
newHeaders.Del("Upgrade")
newHeaders.Del("Connection")
newHeaders.Del("Sec-Websocket-Key")
newHeaders.Del("Sec-Websocket-Version")
newHeaders.Del("Sec-Websocket-Extensions")
newHeaders.Del("Sec-Websocket-Protocol")
dialer := &websocket.Dialer{
NetDialContext: DialContext,
TLSClientConfig: tlsClientConfig,
}
serverConn, resp, err := dialer.DialContext(ctx, r.URL.String(), newHeaders)
if err != nil {
fmt.Printf("wss dial %+v\n", err)
panic(err)
}
clientConn, err := up.Upgrade(w, r, resp.Header)
if err != nil {
fmt.Printf("%+v\n", err)
panic(err)
}
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return wsPumpLoop(ctx, serverConn, clientConn)
})
g.Go(func() error {
return wsPumpLoop(ctx, clientConn, serverConn)
})
err = g.Wait()
if err != nil {
fmt.Printf("%+v\n", err)
panic(err)
}
}
func wsPumpLoop(ctx context.Context, a, b *websocket.Conn) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
mt, p, err := a.ReadMessage()
if err != nil {
return errors.WithStack(err)
}
err = b.WriteMessage(mt, p)
if err != nil {
return errors.WithStack(err)
}
}
}
}