forked from justzx2011/goproxy
/
httproxy.go
108 lines (94 loc) · 1.96 KB
/
httproxy.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
105
106
107
108
package main
import (
"github.com/shell909090/goproxy/sutils"
"net/http"
"strings"
)
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
type Proxy struct {
transport http.Transport
dialer sutils.Dialer
mux *http.ServeMux
}
func NewProxy(dialer sutils.Dialer, mux *http.ServeMux) (p *Proxy) {
p = &Proxy{
dialer: dialer,
transport: http.Transport{Dial: dialer.Dial},
mux: mux,
}
return
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
log.Notice("%s: %s", req.Method, req.URL)
if req.Method == "CONNECT" {
p.Connect(w, req)
return
}
if req.URL.Host == "" {
p.mux.ServeHTTP(w, req)
return
}
req.RequestURI = ""
for _, h := range hopHeaders {
if req.Header.Get(h) != "" {
req.Header.Del(h)
}
}
resp, err := p.transport.RoundTrip(req)
if err != nil {
log.Error("%s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
_, err = sutils.CoreCopy(w, resp.Body)
if err != nil {
log.Error("%s", err)
return
}
return
}
func (p *Proxy) Connect(w http.ResponseWriter, r *http.Request) {
hij, ok := w.(http.Hijacker)
if !ok {
log.Error("httpserver does not support hijacking")
return
}
srcconn, _, err := hij.Hijack()
if err != nil {
log.Error("Cannot hijack connection ", err)
return
}
defer srcconn.Close()
host := r.URL.Host
if !strings.Contains(host, ":") {
host += ":80"
}
dstconn, err := p.dialer.Dial("tcp", host)
if err != nil {
log.Error("dial failed:", err)
srcconn.Write([]byte("HTTP/1.0 502 OK\r\n\r\n"))
return
}
srcconn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
sutils.CopyLink(srcconn, dstconn)
return
}