-
Notifications
You must be signed in to change notification settings - Fork 20
/
http.go
87 lines (67 loc) · 2.07 KB
/
http.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 utils
import (
"net/http"
"net/http/httptest"
"net/http/httputil"
"time"
log "github.com/sirupsen/logrus"
)
var httpHeaderUserAgent = "User-Agent"
func init() {
Validator.RegisterAlias("http_method", "eq=GET|eq=HEAD|eq=POST|eq=PUT|eq=PATCH|eq=DELETE")
}
// HTTPClient is a client for HTTP requests
type HTTPClient struct {
client *http.Client
defaultUserAgent string
}
// NewHTTPClient creates a new HTTP client with our default options
func NewHTTPClient(defaultUserAgent string) *HTTPClient {
return &HTTPClient{
client: &http.Client{
Transport: &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
},
Timeout: time.Duration(15 * time.Second),
},
defaultUserAgent: defaultUserAgent,
}
}
func (c *HTTPClient) prepareRequest(request *http.Request) {
// if user-agent isn't set, use our default
if request.Header.Get(httpHeaderUserAgent) == "" {
request.Header.Set(httpHeaderUserAgent, c.defaultUserAgent)
}
}
// Do does the given HTTP request
func (c *HTTPClient) Do(request *http.Request) (*http.Response, error) {
c.prepareRequest(request)
return c.client.Do(request)
}
// DoWithDump does the given HTTP request and returns a dump of the entire request
func (c *HTTPClient) DoWithDump(request *http.Request) (*http.Response, string, error) {
c.prepareRequest(request)
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, "", err
}
log.Debug(string(dump))
response, err := c.client.Do(request)
return response, string(dump), err
}
// MockWithDump mocks the given HTTP request and returns a dump of the entire request
func (c *HTTPClient) MockWithDump(request *http.Request, mockStatus int, mockResponse string) (*http.Response, string, error) {
c.prepareRequest(request)
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, "", err
}
log.Debug(string(dump))
recorder := httptest.NewRecorder()
recorder.WriteString(mockResponse)
recorder.Code = mockStatus
response := recorder.Result()
response.Request = request
return response, string(dump), nil
}