-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhook.go
More file actions
61 lines (51 loc) · 1.41 KB
/
Copy pathhook.go
File metadata and controls
61 lines (51 loc) · 1.41 KB
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
package xmux
import (
"io"
"net"
"net/http"
"time"
)
func unmarshalError(err error, w http.ResponseWriter, r *http.Request) bool {
return false
}
func handleNotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}
func HandleConnect(w http.ResponseWriter, r *http.Request) {
destConn, err := net.DialTimeout("tcp", r.Host, 10*time.Second)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer destConn.Close()
// 向客户端返回成功响应
w.WriteHeader(http.StatusOK)
// 使用 Hijacker 获取客户端的 TCP 连接
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
clientConn, _, err := hj.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer clientConn.Close()
// 在客户端和目标服务器之间建立双向隧道
go transfer(destConn, clientConn)
transfer(clientConn, destConn)
}
// 数据传输函数
func transfer(destination io.WriteCloser, source io.ReadCloser) {
defer destination.Close()
defer source.Close()
io.Copy(destination, source)
}
func handleOptions(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func handleFavicon(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
}