-
Notifications
You must be signed in to change notification settings - Fork 6
/
ws_server.go
104 lines (85 loc) · 1.76 KB
/
ws_server.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
95
96
97
98
99
100
101
102
103
104
package main
import (
"net"
"net/http"
"net/url"
log "github.com/fangdingjun/go-log/v5"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var dialer = &websocket.Dialer{}
type forwardRule struct {
local string
remote string
}
type wsServer struct {
addr string
rule []forwardRule
}
func (wss *wsServer) run() {
if err := http.ListenAndServe(wss.addr, wss); err != nil {
log.Errorln(err)
}
}
func (wss *wsServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
remote := ""
for _, ru := range wss.rule {
if ru.local == p {
remote = ru.remote
}
}
if remote == "" {
http.Error(w, "not found", http.StatusNotFound)
return
}
ip := r.RemoteAddr
_ip := r.Header.Get("x-real-ip")
if _ip != "" {
ip = _ip
}
log.Debugf("from %s, request %s, forward to %s", ip, p, remote)
defer func() {
log.Debugf("from %s, request finished", ip)
}()
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Errorln(err)
http.Error(w, "bad request", http.StatusBadRequest)
return
}
defer conn.Close()
u, _ := url.Parse(remote)
if u.Scheme == "ws" || u.Scheme == "wss" {
conn1, resp, err := dialer.Dial(remote, nil)
if err != nil {
log.Errorln(err)
return
}
resp.Body.Close()
if resp.StatusCode != http.StatusSwitchingProtocols {
log.Errorf("dial remote ws %d", resp.StatusCode)
return
}
defer conn1.Close()
forwardWS2WS(conn, conn1)
return
}
if u.Scheme == "tcp" {
conn1, err := net.Dial("tcp", u.Host)
if err != nil {
log.Errorln(err)
return
}
defer conn1.Close()
forwardWS2TCP(conn, conn1)
return
}
log.Errorf("unsupported scheme %s", u.Scheme)
}