forked from raviqqe/muffet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirect_http_client.go
65 lines (52 loc) · 1.27 KB
/
redirect_http_client.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
package main
import (
"errors"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
)
type redirectHttpClient struct {
client httpClient
maxRedirections int
}
func newRedirectHttpClient(c httpClient, maxRedirections int) httpClient {
return &redirectHttpClient{c, maxRedirections}
}
func (c *redirectHttpClient) Get(u *url.URL, header http.Header) (httpResponse, error) {
if header == nil {
header = http.Header{}
}
cj, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
for i := range c.maxRedirections + 1 {
for _, c := range cj.Cookies(u) {
header.Add("cookie", c.String())
}
r, err := c.client.Get(u, header)
if err != nil && i == 0 {
return nil, err
} else if err != nil {
return nil, fmt.Errorf("%w (following redirect %v)", err, u.String())
} else if c := r.StatusCode(); c < 300 || c >= 400 {
return r, nil
}
s := r.Header("Location")
if len(s) == 0 {
return nil, errors.New("location header not set")
}
u, err = u.Parse(s)
if err != nil {
return nil, err
}
cj.SetCookies(u, parseCookies(r.Header("set-cookie")))
}
return nil, errors.New("too many redirections")
}
func parseCookies(s string) []*http.Cookie {
h := http.Header{}
h.Add("cookie", s)
return (&http.Request{Header: h}).Cookies()
}