-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproxy.go
More file actions
65 lines (55 loc) · 1.25 KB
/
proxy.go
File metadata and controls
65 lines (55 loc) · 1.25 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
62
63
64
65
package gserv
import (
"net/http"
"net/http/httputil"
"strings"
)
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Accept-Encoding",
"Upgrade",
}
func ProxyHandler(host string, pathFn func(ctx *Context, path string) (string, error)) Handler {
rp := &httputil.ReverseProxy{}
scheme := "http"
if strings.HasPrefix(host, "http://") {
host = host[7:]
} else if strings.HasPrefix(host, "https://") {
scheme = "https"
host = host[8:]
}
rp.Director = func(req *http.Request) {
req.URL.Scheme = scheme
req.URL.Host = host
req.Host = ""
h := req.Header
if _, ok := h["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
for _, hh := range hopHeaders {
h.Del(hh)
}
h.Set("X-Forwarded-For", req.RemoteAddr)
}
rp.ModifyResponse = func(r *http.Response) error {
return nil
}
return func(ctx *Context) Response {
if pathFn != nil {
p, err := pathFn(ctx, ctx.Req.URL.Path)
if err != nil {
return NewJSONErrorResponse(http.StatusBadRequest, err)
}
ctx.Req.URL.Path = p
}
rp.ServeHTTP(ctx, ctx.Req)
return nil
}
}