-
Notifications
You must be signed in to change notification settings - Fork 3
/
request_builder.go
44 lines (37 loc) · 1.08 KB
/
request_builder.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
package rclient
import (
"bytes"
"encoding/json"
"net/http"
)
// A RequestBuilder creates a *http.Request from the given parameters.
// It is important that each option gets added to the generated request:
// req, _ := http.NewRequest(...)
// for _, option := range options
// if err := option(req); err != nil {
// return nil, err
// }
// }
type RequestBuilder func(method, url string, body interface{}, options ...RequestOption) (*http.Request, error)
// BuildJSONRequest creates a new *http.Request with the specified method, url and body in JSON format.
func BuildJSONRequest(method, url string, body interface{}, options ...RequestOption) (*http.Request, error) {
b := new(bytes.Buffer)
if body != nil {
if err := json.NewEncoder(b).Encode(body); err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, b)
if err != nil {
return nil, err
}
if b.Len() > 0 {
req.Header.Add("content-type", "application/json")
}
for _, option := range options {
if err := option(req); err != nil {
return nil, err
}
}
return req, nil
}