-
Notifications
You must be signed in to change notification settings - Fork 7
/
httpClient.go
94 lines (82 loc) · 2.18 KB
/
httpClient.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 main
import (
"log"
"net"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
)
////////////////////////////////////////////////////////////////////////////////
// httpClient
////////////////////////////////////////////////////////////////////////////////
// httpClient implements the Runner interface
type httpClient struct {
connectWS string
listenTCP string
}
// NewHTTPClient creates a new TCP server which connects tunnels to an HTTP server
func NewHTTPClient(listenTCP, connectWS string) Runner {
return &httpClient{
connectWS: connectWS,
listenTCP: listenTCP,
}
}
func (h *httpClient) Run() error {
tcpConnection, err := net.Listen("tcp", h.listenTCP)
if err != nil {
return err
}
defer tcpConnection.Close()
log.Printf("Listening to %s", h.listenTCP)
for {
tcpConn, err := tcpConnection.Accept()
if err != nil {
log.Printf("Error: could not accept the connection: %s", err)
continue
}
wsConn, err := h.createWsConnection(tcpConn.RemoteAddr().String())
if err != nil || wsConn == nil {
log.Printf("%s - Error while dialing %s: %s", tcpConn.RemoteAddr(), h.connectWS, err)
tcpConn.Close()
continue
}
b := NewBidirConnection(tcpConn, wsConn, time.Second*10)
go b.Run()
}
}
func (h *httpClient) toWsURL(asString string) (string, error) {
asURL, err := url.Parse(asString)
if err != nil {
return asString, err
}
switch asURL.Scheme {
case "http":
asURL.Scheme = "ws"
case "https":
asURL.Scheme = "wss"
}
return asURL.String(), nil
}
func (h *httpClient) createWsConnection(remoteAddr string) (wsConn *websocket.Conn, err error) {
url := h.connectWS
for {
var wsURL string
wsURL, err = h.toWsURL(url)
if err != nil {
return
}
log.Printf("%s - Connecting to %s", remoteAddr, wsURL)
var httpResponse *http.Response
wsConn, httpResponse, err = websocket.DefaultDialer.Dial(wsURL, nil)
if httpResponse != nil {
switch httpResponse.StatusCode {
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
url = httpResponse.Header.Get("Location")
log.Printf("%s - Redirect to %s", remoteAddr, url)
continue
}
}
return
}
}