/
basic_http_client.go
113 lines (101 loc) · 2.49 KB
/
basic_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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package client
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/pkg/errors"
)
// ErrNotFound Error for not found
var ErrNotFound = errors.New("unexpected response code, got 404")
// ErrUnprocessableEntity Error for and unprocessable entity
var ErrUnprocessableEntity = errors.New("unexpected response code, got 422")
// BasicHTTPClient handles basic http sending logic and cookie handling
type BasicHTTPClient struct {
BaseURL string
HttpClient *http.Client
Cookies []*http.Cookie
Header http.Header
}
// NewBasicHTTPClient returns new basic http client configured with an base URL
func NewBasicHTTPClient(c *http.Client, baseURL string) *BasicHTTPClient {
return &BasicHTTPClient{
BaseURL: baseURL,
HttpClient: c,
Cookies: make([]*http.Cookie, 0),
}
}
// Do executes a method on an endpoint with an optional body
// and checks that an expected status code is returned
func (em *BasicHTTPClient) Do(
method,
endpoint string,
body interface{},
obj interface{},
expectedStatusCode int,
) (*http.Response, error) {
b, err := json.Marshal(body)
if body != nil && err != nil {
return nil, err
}
return em.doRaw(method, endpoint, b, obj, expectedStatusCode)
}
func (em *BasicHTTPClient) doRaw(
method,
endpoint string,
body []byte, obj interface{},
expectedStatusCode int,
) (*http.Response, error) {
client := em.HttpClient
req, err := http.NewRequest(
method,
fmt.Sprintf("%s%s", em.BaseURL, endpoint),
bytes.NewBuffer(body),
)
if err != nil {
return nil, err
}
for _, cookie := range em.Cookies {
req.AddCookie(cookie)
}
req.Header = em.Header
resp, err := client.Do(req)
if err != nil {
return resp, err
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf(
"error while reading response: %v\nURL: %s\nresponse received: %s",
err,
em.BaseURL,
string(b),
)
}
if resp.StatusCode == http.StatusNotFound {
return resp, ErrNotFound
} else if resp.StatusCode == http.StatusUnprocessableEntity {
return resp, ErrUnprocessableEntity
} else if resp.StatusCode != expectedStatusCode {
return resp, fmt.Errorf(
"unexpected response code, got %d, expected 200\nURL: %s\nresponse received: %s",
resp.StatusCode,
em.BaseURL,
string(b),
)
}
if obj == nil {
return resp, err
}
err = json.Unmarshal(b, &obj)
if err != nil {
return nil, fmt.Errorf(
"error while unmarshaling response: %v\nURL: %s\nresponse received: %s",
err,
em.BaseURL,
string(b),
)
}
return resp, err
}