-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequester.go
More file actions
98 lines (80 loc) · 1.9 KB
/
requester.go
File metadata and controls
98 lines (80 loc) · 1.9 KB
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
88
89
90
91
92
93
94
95
96
97
98
package letsrest
import (
"io"
"io/ioutil"
"net/http"
"sort"
"strings"
"time"
)
type Requester interface {
Do(request *RequestData) (*Response, error)
}
const defaultBodyLimit int64 = 1024 * 1024 * 10 // 10MB
func NewHTTPRequester(maxBodySize ...int64) *HTTPRequester {
limit := defaultBodyLimit
if len(maxBodySize) > 0 {
limit = maxBodySize[0]
}
return &HTTPRequester{
maxBodySize: limit,
client: newHTTPClient(),
}
}
func newHTTPClient() *HTTPClientDefault {
return &HTTPClientDefault{
client: http.DefaultClient,
}
}
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
type HTTPClientDefault struct {
client *http.Client
}
func (c *HTTPClientDefault) Do(req *http.Request) (*http.Response, error) {
return c.client.Do(req)
}
type HTTPRequester struct {
maxBodySize int64
client HTTPClient
}
func (r *HTTPRequester) Do(request *RequestData) (cResp *Response, err error) {
var reader io.Reader
if len(request.Body) > 0 {
reader = strings.NewReader(request.Body)
}
req, err := http.NewRequest(request.Method, request.URL, reader)
if err != nil {
return nil, err
}
for _, header := range request.Headers {
req.Header.Add(header.Name, header.Value)
}
start := time.Now()
resp, err := r.client.Do(req)
if err != nil {
return nil, err
}
var h HeaderSlice
for key, value := range resp.Header {
h = append(h, Header{Name: key, Value: strings.Join(value, ", ")})
}
sort.Sort(h)
contentTypeHeader := findHeader("Content-Type", h)
contentType := ""
if contentTypeHeader != nil {
contentType = contentTypeHeader.Value
}
limitedReader := &LimitedErrReader{N: r.maxBodySize, R: resp.Body}
bodyData, err := ioutil.ReadAll(limitedReader)
cResp = &Response{
StatusCode: resp.StatusCode,
Headers: h,
BodyLen: len(bodyData),
Body: string(bodyData),
ContentType: contentType,
Duration: time.Now().Sub(start),
}
return
}