-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproxy_test.go
42 lines (39 loc) · 1.17 KB
/
proxy_test.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
package request_test
import (
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
)
func CreateTestProxy(suite *RequestSuite) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
log := suite.Logger.Child("proxy", "handler")
headers := map[string]string{}
for key, values := range req.Header {
headers[key] = strings.Join(values, ", ")
}
log.Record("headers", headers).Infof("Request: %s %s", req.Method, req.URL)
log.Infof("Proxying to %s", req.URL)
client := &http.Client{}
req.RequestURI = ""
if remoteIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
log.Infof("Proxying from %s", remoteIP)
req.Header.Set("X-Forwarded-For", remoteIP)
}
proxyRes, err := client.Do(req)
if err != nil {
log.Errorf("Failed to proxy", err)
http.Error(res, "Proxy Error", http.StatusBadGateway)
}
defer proxyRes.Body.Close()
for key, values := range proxyRes.Header {
for _, value := range values {
res.Header().Add(key, value)
}
}
log.Infof("Replying to client (HTTP %s)", proxyRes.Status)
res.WriteHeader(proxyRes.StatusCode)
_, _ = io.Copy(res, proxyRes.Body)
}))
}