-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_proxy.go
52 lines (45 loc) · 1.12 KB
/
http_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
package do
import (
"net/http"
"net/http/httputil"
"net/url"
)
type HTTPProxyOption struct {
Director func(req *http.Request)
ModifyResponse func(r *http.Response) error
ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
}
func (opt *HTTPProxyOption) complete(rp *httputil.ReverseProxy) {
if rp == nil {
return
}
if opt != nil {
if opt.Director != nil {
rp.Director = opt.Director
}
if opt.ModifyResponse != nil {
rp.ModifyResponse = opt.ModifyResponse
}
if opt.ErrorHandler != nil {
rp.ErrorHandler = opt.ErrorHandler
}
}
}
// HTTPProxy listen localAddr and transfer any request to remoteAddr. We can use handlers to specify one custom func to transfer data.
func HTTPProxy(localAddr, remoteAddr string, opt *HTTPProxyOption) (err error) {
url, err := url.Parse(remoteAddr)
if err != nil {
return err
}
rp := httputil.NewSingleHostReverseProxy(url)
opt.complete(rp)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
rp.ServeHTTP(w, r)
})
s := &http.Server{
Addr: localAddr,
Handler: mux,
}
return s.ListenAndServe()
}