-
Notifications
You must be signed in to change notification settings - Fork 1
/
requests.go
254 lines (217 loc) · 6.54 KB
/
requests.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package requests
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
// HTTPMethod is a type that represents an
// HTTP request method.
// Read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
type HTTPMethod int
// Enums representing HTTP methods
const (
GET HTTPMethod = iota // An HTTP GET method
POST // An HTTP POST method
PUT // An HTTP PUT method
DELETE // An HTTP DELETE method
OPTIONS // An HTTP OPTIONS method
HEAD // An HTTP HEAD method
CONNECT // An HTTP CONNECT method
TRACE // An HTTP TRACE method
PATCH // An HTTP PATCH method
)
// Convert an HTTPMethod to it's string format
func (m HTTPMethod) String() string {
switch m {
case GET:
return "GET"
case POST:
return "POST"
case PUT:
return "PUT"
case DELETE:
return "DELETE"
case OPTIONS:
return "OPTIONS"
case HEAD:
return "HEAD"
case CONNECT:
return "CONNECT"
case TRACE:
return "TRACE"
case PATCH:
return "PATCH"
}
return ""
}
// Request is a type that represents an HTTP request
type Request struct {
URL string // URL to send the request to
Method HTTPMethod // HTTP method to use
Headers map[string]string // Headers to send with the request
Body []byte // Body to send with the request
Timeout time.Duration // Timeout for the request
}
// NewGetRequest creates a new Request object
// with the supplied URL and sets the HTTP method
// to GET.
func NewGetRequest(url string) *Request {
return &Request{
URL: url,
Method: GET,
}
}
// SendGetRequest creates a new HTTP GET request
// and sends it to the specified URL.
// Internally, calls `NewGetRequest(url).Send()`
func SendGetRequest(url string) (*Response, error) {
return NewGetRequest(url).Send()
}
// NewPostRequest creates a new Request object
// with the supplied URL, content-type header, and body sets the HTTP method
// to POST.
func NewPostRequest(url string, contentType string, body []byte) *Request {
return &Request{
URL: url,
Method: POST,
Headers: map[string]string{"content-type": contentType},
Body: body,
}
}
// SendPostRequest creates a new HTTP POST request
// and sends it to the specified URL.
// Internally, calls `NewPostRequest(url, contentType, body).Send()`
func SendPostRequest(url string, contentType string, body []byte) (*Response, error) {
return NewPostRequest(url, contentType, body).Send()
}
// getReqBody returns the request body as a buffer that can be
// passed to the http.NewRequest function
func (req *Request) getReqBody() *bytes.Buffer {
return bytes.NewBuffer(req.Body)
}
// GetHeader gets a header value from the request. Normalizes the key
// to lowercase before checking. Returns the value of the
// header and whether it exists.
func (req *Request) GetHeader(name string) (string, bool) {
// Create the map if it doesn't exist
if req.Headers == nil {
req.Headers = make(map[string]string)
}
// Normalize the key (convert to lowercase)
key := strings.ToLower(name)
// Return the header and whether it exists
value, ok := req.Headers[key]
return value, ok
}
// SetHeader sets a header value in the request. Normalizes the key
// before setting (converts to lowercase).
func (req *Request) SetHeader(name, value string) {
// Create the map if it doesn't exist
if req.Headers == nil {
req.Headers = make(map[string]string)
}
// Normalize the key (convert to lowercase)
key := strings.ToLower(name)
// Add the header to the Headers map
req.Headers[key] = value
}
// DelHeader deletes a header value from the request headers
// if it exists. Normalizes the key to lowercase
// before deleting.
func (req *Request) DelHeader(name string) {
// Create the map if it doesn't exist
if req.Headers == nil {
req.Headers = make(map[string]string)
}
// Normalize the key (convert to lowercase)
key := strings.ToLower(name)
// Delete the header if it exists
delete(req.Headers, key)
}
// Send sends the HTTP request with the supplied parameters
func (req *Request) Send() (*Response, error) {
// Create an http client (with optional timeout)
client := http.Client{
Timeout: req.Timeout,
}
// Create the underlying request
httpRequest, err := http.NewRequest(req.Method.String(), req.URL, req.getReqBody())
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
// Set the headers in the underlying request
for k, v := range req.Headers {
httpRequest.Header.Set(k, v)
}
// Make the reuquest
httpResponse, err := client.Do(httpRequest)
if err != nil {
return nil, err
}
// Add return headers
rHeaders := make(map[string]string)
for k, v := range httpResponse.Header {
lowerKey := strings.ToLower(k)
rHeaders[lowerKey] = v[0]
}
// Load the request body
defer httpResponse.Body.Close()
body, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return nil, err
}
// Format the response & return
resp := Response{
Ok: httpResponse.StatusCode < 400,
StatusCode: httpResponse.StatusCode,
Headers: rHeaders,
Body: body,
}
return &resp, nil
}
// MustSend sends the HTTP request and panic if an error is returned.
// (Calls Send() internally)
func (req *Request) MustSend() *Response {
resp, err := req.Send()
if err != nil {
panic(err)
}
return resp
}
// Response is a type that represents an HTTP response
// returned from an HTTP request
type Response struct {
Ok bool // Was the request successful? (Status codes: 200-399)
StatusCode int // HTTP response status code
Headers map[string]string // HTTP Response headers
Body []byte // HTTP Response body
}
// GetHeader gets a header value from the response if it exists.
// Normalizes the key to lowercase before checking.
// Returns the value of the header and whether it exists.
func (resp *Response) GetHeader(name string) (string, bool) {
// Create the map if it doesn't exist
if resp.Headers == nil {
resp.Headers = make(map[string]string)
}
// Normalize the key (convert to lowercase)
key := strings.ToLower(name)
// Return the header and whether it exists
value, ok := resp.Headers[key]
return value, ok
}
// JSON unmarshalls the response body into a map
func (resp *Response) JSON() (map[string]interface{}, error) {
// Create a new map to store the JSON data
data := make(map[string]interface{})
// Unmarshal the JSON data
err := json.Unmarshal(resp.Body, &data)
if err != nil {
return nil, err
}
return data, nil
}