-
Notifications
You must be signed in to change notification settings - Fork 251
/
proxy.go
73 lines (59 loc) · 1.43 KB
/
proxy.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
package expose
import (
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
type exposeProxy interface {
// stop the proxy
Close() error
}
type httpProxy struct {
server *http.Server
}
// Start a proxy running on all interfaces on this host, at an arbitrary port,
// forwarding traffic to the given port on localhost.
func proxyHTTP(listener net.Listener, targetPort uint16) (exposeProxy, error) {
targetURL, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", targetPort))
proxy := httputil.NewSingleHostReverseProxy(targetURL)
// We want to support streaming responses that are not detected as such (for
// example, a streaming logfile). So, arrange to flush any buffered data after
// 100ms.
proxy.FlushInterval = 100 * time.Millisecond
server := &http.Server{
Handler: websockCompatibleHandlerFunc(proxy, targetPort),
}
go func() {
_ = server.Serve(listener)
}()
return &httpProxy{server}, nil
}
func (p *httpProxy) Close() error {
err := p.server.Close()
if err != nil {
return err
}
return nil
}
type tcpPortProxy struct {
server *http.Server
}
func proxyTCPPort(listener net.Listener, targetPort uint16) (exposeProxy, error) {
server := &http.Server{
Handler: websocketToTCPHandlerFunc(targetPort),
}
go func() {
_ = server.Serve(listener)
}()
return &tcpPortProxy{server}, nil
}
func (p *tcpPortProxy) Close() error {
err := p.server.Close()
if err != nil {
return err
}
return nil
}