-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathproxy_test.go
55 lines (47 loc) · 1.12 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
43
44
45
46
47
48
49
50
51
52
53
54
55
package httpclient_test
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/circleci/ex/closer"
)
type fwdProxy struct {
URL string
ProxiedURL string
}
func startFwdProxy(t *testing.T) *fwdProxy {
p := &fwdProxy{}
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect { // tunnelling not supported
w.WriteHeader(http.StatusServiceUnavailable)
return
} else {
p.handleHTTP(w, r)
}
}))
p.URL = server.URL
t.Cleanup(server.Close)
return p
}
func (p *fwdProxy) handleHTTP(w http.ResponseWriter, r *http.Request) {
p.ProxiedURL = r.URL.String()
t := http.DefaultTransport.(*http.Transport).Clone()
t.DialContext = localhostDialler()
t.Proxy = nil
//nolint:bodyclose // handled by closer
resp, err := t.RoundTrip(r)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer closer.ErrorHandler(resp.Body, &err)
for k, vv := range w.Header() {
for _, v := range vv {
resp.Header.Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
}