This repository has been archived by the owner on Nov 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (80 loc) · 2.11 KB
/
main.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package unfurl
import (
"errors"
"net/http"
"net/http/cookiejar"
"net/url"
)
// Client represents a unfurl client instance
type Client struct {
httpClient *http.Client
options Options
}
// Options exposes internal settings to change the Client behaviour
type Options struct {
// MaxHops defines how many redirects the client can suffer before returning
// an error
MaxHops int
// UserAgent defines the UserAgent value used by the underlying http client
UserAgent *string
}
// ErrTooManyRedirects indicates that the unfurl client has archieved the
// maximum allowed request count defined by the Options struct
var ErrTooManyRedirects = errors.New("Too many redirects")
// NewClientWithOptions returns a new instance of a Client using the provided
// Options values
func NewClientWithOptions(opts Options) Client {
return Client{
options: opts,
httpClient: &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
},
}
}
// NewClient returns a new instance of a Client using the default values for
// the settings parameters.
// (MaxHops: 20)
// (UserAgent: nil)
func NewClient() Client {
return NewClientWithOptions(Options{MaxHops: 20})
}
// Process attempts to follow all possible redirects of a given URL
func (c *Client) Process(in string) (string, error) {
jar, _ := cookiejar.New(nil)
c.httpClient.Jar = jar
hops := 0
for {
req, err := http.NewRequest("GET", in, nil)
if err != nil {
return "", err
}
if c.options.UserAgent != nil {
req.Header.Set("User-Agent", *c.options.UserAgent)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if _, ok := resp.Header["Location"]; ok && resp.StatusCode/100.0 == 3 {
if hops >= c.options.MaxHops {
return "", ErrTooManyRedirects
}
hops++
base, err := url.Parse(in)
if err != nil {
return "", err
}
next, err := url.Parse(resp.Header["Location"][0])
if err != nil {
return "", err
}
in = base.ResolveReference(next).String()
continue
} else {
return resp.Request.URL.String(), nil
}
}
}