-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathreverseproxy.go
More file actions
67 lines (61 loc) · 2.18 KB
/
reverseproxy.go
File metadata and controls
67 lines (61 loc) · 2.18 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
66
67
package reverseproxy
import (
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
// Build initializes and returns a new ReverseProxy instance suitable for SSL proxying
func Build(toURL *url.URL, ipFilter string) *httputil.ReverseProxy {
localProxy := &httputil.ReverseProxy{}
addProxyHeaders := func(req *http.Request) {
req.Header.Set(http.CanonicalHeaderKey("X-Forwarded-Proto"), "https")
req.Header.Set(http.CanonicalHeaderKey("X-Forwarded-Port"), "443") // TODO: inherit another port if needed
}
localProxy.Director = newDirector(toURL, ipFilter, addProxyHeaders)
return localProxy
}
// newDirector creates a base director that should be exactly what http.NewSingleHostReverseProxy() creates, but allows
// for the caller to supply and extraDirector function to decorate to request to the downstream server
func newDirector(target *url.URL, ipFilter string, extraDirector func(*http.Request)) func(*http.Request) {
targetQuery := target.RawQuery
return func(req *http.Request) {
remoteIp, _, _ := net.SplitHostPort(req.RemoteAddr)
if ipFilter == "" || remoteIp == ipFilter {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
if extraDirector != nil {
extraDirector(req)
}
} else {
// send to black hole
req.URL.Host = "127.0.0.1:0"
req.URL.Scheme = "http"
}
}
}
// singleJoiningSlash is a utility function that adds a single slash to a URL where appropriate, copied from
// the httputil package
// TODO: add test to ensure behavior does not diverge from httputil's implementation, as per Rob Pike's proverbs
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}