-
Notifications
You must be signed in to change notification settings - Fork 3
/
redirect-follower.go
51 lines (44 loc) · 1.15 KB
/
redirect-follower.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
package registryproxy
import (
"net/http"
)
type ctxKey int
// context keys
const (
CtxPath ctxKey = 0
)
// RedirectFollower represents a Transport RoundTripper that follows redirects
type RedirectFollower struct {
http.RoundTripper
}
// NewRedirectFollower wraps another http.RoundTripper following redirect response codes
func NewRedirectFollower(wrappedRoundTripper http.RoundTripper) http.RoundTripper {
return &RedirectFollower{
RoundTripper: wrappedRoundTripper,
}
}
// RoundTrip implements http.RoundTripper
func (t *RedirectFollower) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.RoundTripper.RoundTrip(req)
if err != nil {
return resp, err
}
// follow redirects
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
l, err := resp.Location()
if err != nil {
return resp, err
}
// cContext := context.WithValue(req.Context(), CtxPath, req.URL.Path)
cReq := req.Clone(req.Context())
resp.Request = cReq
cReq.Header = http.Header{}
cReq.URL = l
cReq.Host = l.Host
cReq.RequestURI = l.RequestURI()
cReq.Header.Set("X-Forwarded-Host", l.Host)
resp.Request = cReq
return resp, err
}
return resp, err
}