forked from raviqqe/muffet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fasthttp_http_client.go
60 lines (47 loc) · 1.15 KB
/
fasthttp_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
package main
import (
"errors"
"fmt"
"net/url"
"time"
"github.com/valyala/fasthttp"
)
type fasthttpHTTPClient struct {
client *fasthttp.Client
maxRedirections int
timeout time.Duration
}
func newFasthttpHTTPClient(c *fasthttp.Client, maxRedirections int, timeout time.Duration) httpClient {
return &fasthttpHTTPClient{c, maxRedirections, timeout}
}
func (c *fasthttpHTTPClient) Get(u *url.URL, headers map[string]string) (httpResponse, error) {
req, res := fasthttp.Request{}, fasthttp.Response{}
req.SetRequestURI(u.String())
req.SetConnectionClose()
for k, v := range headers {
req.Header.Add(k, v)
}
i := 0
for {
err := c.client.DoTimeout(&req, &res, c.timeout)
if err != nil {
return nil, err
}
switch res.StatusCode() / 100 {
case 2:
return newFasthttpHTTPResponse(req.URI(), &res), nil
case 3:
i++
if i > c.maxRedirections {
return nil, errors.New("too many redirections")
}
u := res.Header.Peek("Location")
if len(u) == 0 {
return nil, errors.New("location header not found")
}
req.URI().UpdateBytes(u)
default:
return nil, fmt.Errorf("%v", res.StatusCode())
}
}
}