/
proxy.go
208 lines (178 loc) · 6.23 KB
/
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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package proxy
import (
"log"
"net"
"net/http"
"net/http/httputil"
"regexp"
"strings"
"time"
"github.com/integralist/go-reverse-proxy/routing"
)
var responseHeaders = []string{
"X-Forwarded-Host",
"X-Origin-Host",
"X-Router-Upstream",
"X-Router-Upstream-OriginalHost",
"X-Router-Upstream-OriginalPath",
"X-Router-Upstream-OriginalPathModified",
"X-Router-Upstream-Override",
"X-Router-Upstream-OverrideHost",
"X-Router-Upstream-OverridePath",
}
// GenerateProxy returns a unique reverse proxy instance which includes logic
// for handling override behaviour for configuration routes.
func GenerateProxy(conf routing.Config) http.Handler {
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.Header.Add("X-Router-Upstream", conf.Upstream.Name)
req.Header.Add("X-Router-Upstream-OriginalHost", conf.Upstream.Host)
req.Header.Add("X-Router-Upstream-OriginalPath", req.URL.Path)
req.Header.Add("X-Forwarded-Host", req.Host)
req.Header.Add("X-Origin-Host", conf.Upstream.Host)
// This was done to unblock the ability to test the code, but it would be
// better if there were no references to testing within the code itself,
// so I think the only way to solve this would be to inject the
// modifications as a func dependency so we could modify the request
// object differently depending on the runtime environment context.
if req.Header.Get("X-Testing") != "true" {
req.URL.Scheme = "https"
}
// some upstreams will reject a request if the given Host HTTP header
// isn't recognised, and so we always make sure to tweak that header
// so it isn't set to the proxy's host value, but set to the upsteam's.
req.Host = conf.Upstream.Host
req.URL.Host = conf.Upstream.Host
if conf.ModifyPath != "" {
modifyPath(req, conf.ModifyPath)
}
if conf.Override.Header != "" && conf.Override.Match != "" {
overrideHeader(req, conf.Override)
}
if conf.Override.Query != "" && conf.Override.Match != "" {
overrideQuery(req, conf.Override)
}
cleanUpQueryString(req)
log.Printf("request: %s\n", req.URL)
},
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
},
ModifyResponse: func(r *http.Response) error {
for _, header := range responseHeaders {
value := r.Request.Header.Get(header)
if value != "" {
r.Header.Set(header, value)
}
}
return nil
},
}
return proxy
}
func modifyPath(req *http.Request, modifyPath string) {
if strings.Contains(modifyPath, "$") {
req.URL.Path = modifyPath
for k, v := range req.URL.Query() {
// req.URL.Query() = map[foo:[ncg_foovalue] bar:[ncg_barvalue]]
isCaptureGroup := strings.HasPrefix(k, "ncg_")
if isCaptureGroup {
// interpolate query param value into modified request path
cleanKeyPrefix := strings.Replace(k, "ncg_", "", 1)
// replace ${foo} with foo
r := strings.NewReplacer("$", "", "{", "", "}", "", cleanKeyPrefix, v[0])
req.URL.Path = r.Replace(req.URL.Path)
}
}
} else {
req.URL.Path = modifyPath
}
req.Header.Add("X-Router-Upstream-OriginalPathModified", req.URL.Path)
}
func overrideHeader(req *http.Request, override routing.Override) {
if req.Header.Get(override.Header) == override.Match {
if override.ModifyPath != "" {
// TODO: duplicated logic with modifyPath function
if strings.Contains(override.ModifyPath, "$") {
req.URL.Path = override.ModifyPath
for k, v := range req.URL.Query() {
// req.URL.Query() = map[foo:[ncg_foovalue] bar:[ncg_barvalue]]
isCaptureGroup := strings.HasPrefix(k, "ncg_")
if isCaptureGroup {
// interpolate query param value into modified request path
cleanKeyPrefix := strings.Replace(k, "ncg_", "", 1)
// replace ${foo} with foo
r := strings.NewReplacer("$", "", "{", "", "}", "", cleanKeyPrefix, v[0])
req.URL.Path = r.Replace(req.URL.Path)
}
}
} else {
req.URL.Path = override.ModifyPath
}
req.Header.Add("X-Router-Upstream-OverridePath", req.URL.Path)
}
if override.Upstream != nil && override.Upstream.Host != "" && override.Upstream.Name != "" {
req.Host = override.Upstream.Host
req.URL.Host = override.Upstream.Host
req.Header.Add("X-Router-Upstream-Override", override.Upstream.Name)
req.Header.Add("X-Router-Upstream-OverrideHost", override.Upstream.Host)
}
}
}
func overrideQuery(req *http.Request, override routing.Override) {
param := req.URL.Query().Get(override.Query)
if override.MatchType == "regex" {
// TODO: figure out how to precompile this rather than at runtime
pattern, err := regexp.Compile(override.Match)
if err != nil {
return
}
match := pattern.MatchString(param)
if match {
if override.Upstream != nil {
req.Host = override.Upstream.Host
req.URL.Host = override.Upstream.Host
req.Header.Add("X-Router-Upstream-OverrideHost", req.URL.Host)
}
if override.ModifyPath != "" {
newpath := []byte{}
queryparam := []byte(param)
template := []byte(override.ModifyPath)
for _, submatches := range pattern.FindAllSubmatchIndex(queryparam, -1) {
newpath = pattern.Expand(newpath, template, queryparam, submatches)
}
req.URL.Path = string(newpath)
req.Header.Add("X-Router-Upstream-OverridePath", req.URL.Path)
}
}
} else {
if param == override.Match {
if override.Upstream != nil {
req.Host = override.Upstream.Host
req.URL.Host = override.Upstream.Host
req.Header.Add("X-Router-Upstream-OverrideHost", req.URL.Host)
}
if override.ModifyPath != "" {
req.URL.Path = override.ModifyPath
req.Header.Add("X-Router-Upstream-OverridePath", req.URL.Path)
}
}
}
}
// cleanUpQueryString removes any named capture groups from the query string
// that were added by our routing logic. The capture groups were added to the
// query string so that the final request handler could easily parse the values
// and interpolate them into a modified request path, but after that they are
// not useful to either the client nor the proxied upstream.
func cleanUpQueryString(req *http.Request) {
for k := range req.URL.Query() {
isCaptureGroup := strings.HasPrefix(k, "ncg_")
if isCaptureGroup {
originalQuery := req.URL.Query()
originalQuery.Del(k)
req.URL.RawQuery = originalQuery.Encode()
}
}
}