-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathredirect.go
47 lines (40 loc) · 1.11 KB
/
redirect.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
package kala
import (
"fmt"
"gopkg.in/resty.v1"
"net"
"net/http"
"strings"
)
var (
hdrUserAgentValue = "go-resty v%s - https://github.com/go-resty/resty"
hdrUserAgentKey = http.CanonicalHeaderKey("User-Agent")
)
func FlexibleRedirectPolicy(noOfRedirect int) resty.RedirectPolicy {
return resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
if len(via) >= noOfRedirect {
return fmt.Errorf("Stopped after %d redirects", noOfRedirect)
}
checkHostAndAddHeaders(req, via[0])
return nil
})
}
func getHostname(host string) (hostname string) {
if strings.Index(host, ":") > 0 {
host, _, _ = net.SplitHostPort(host)
}
hostname = strings.ToLower(host)
return
}
func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) {
curHostname := getHostname(cur.URL.Host)
preHostname := getHostname(pre.URL.Host)
cur.Method = pre.Method
if strings.EqualFold(curHostname, preHostname) {
for key, val := range pre.Header {
cur.Header[key] = val
}
} else { // only library User-Agent header is added
cur.Header.Set(hdrUserAgentKey, fmt.Sprintf(hdrUserAgentValue, "1.0"))
}
}