/
client.go
94 lines (78 loc) · 1.63 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package client
import (
"context"
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"github.com/gorilla/websocket"
)
type Client struct {
ctx context.Context
localAddr string
remoteAddr string
viaAddr string
headers http.Header
errCh chan error
}
func NewClient(
ctx context.Context,
localAddr string,
remoteAddr string,
viaAddr string,
errCh chan error,
) *Client {
return &Client{
ctx: ctx,
localAddr: localAddr,
remoteAddr: remoteAddr,
viaAddr: viaAddr,
headers: http.Header{},
errCh: errCh,
}
}
func (c *Client) SetHeader(key, value string) {
c.headers.Set(key, value)
}
func (c *Client) ListenAndServe() error {
listener, err := net.Listen("tcp", c.localAddr)
if err != nil {
return fmt.Errorf("error listening on %s: %w", c.localAddr, err)
}
defer listener.Close()
go func() {
<-c.ctx.Done()
listener.Close()
}()
for c.ctx.Err() == nil {
localConn, err := listener.Accept()
if err != nil {
if c.errCh != nil {
c.errCh <- fmt.Errorf("error accepting local connection: %w", err)
}
continue
}
go func() {
defer localConn.Close()
wsConn, _, err := websocket.DefaultDialer.DialContext(
c.ctx,
c.viaAddr+"/tunnels/"+base64encode(c.remoteAddr),
c.headers,
)
if err != nil {
if c.errCh != nil {
c.errCh <- fmt.Errorf("error dialing WebSocket server: %w", err)
}
return
}
defer wsConn.Close()
go func() { io.Copy(wsConn.UnderlyingConn(), localConn) }()
io.Copy(localConn, wsConn.UnderlyingConn())
}()
}
return c.ctx.Err()
}
func base64encode(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}