-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
95 lines (87 loc) · 2.26 KB
/
request.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
package httpclient
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"github.com/pkg/errors"
)
// For ease of unit testing.
// Declaring these functions as global variables
// makes it easy to mock them.
var (
jsonEncode = func(w io.Writer, data any) error {
return json.NewEncoder(w).Encode(data)
}
newRequestWithContext = http.NewRequestWithContext
)
// NewRequest returns an *http.Request.
func NewRequest(ctx context.Context, method, url string) (*http.Request, error) {
req, err := newRequestWithContext(ctx, method, url, nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
return req, nil
}
// NewRequestWithHeaders returns an *http.Request with
// specified headers.
func NewRequestWithHeaders(ctx context.Context, method, url string,
headers map[string]string) (*http.Request, error) {
req, err := newRequestWithContext(ctx, method, url, nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
for k, v := range headers {
req.Header.Add(k, v)
}
return req, nil
}
// NewJsonRequest returns an *http.Request with a json encoded body.
func NewJsonRequest(ctx context.Context, method,
url string, data any) (*http.Request, error) {
body, err := body(data)
if err != nil {
return nil, err
}
req, err := newRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header = http.Header{
"Content-Type": {"application/json"},
}
return req, nil
}
// NewJsonRequestWithHeaders returns an *http.Request with a json encoded body
// and specified headers.
func NewJsonRequestWithHeaders(ctx context.Context, method, url string,
data any, headers map[string]string) (*http.Request, error) {
req, err := NewJsonRequest(ctx, method, url, data)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Add(k, v)
}
return req, nil
}
// body returns the appropriate payload.
func body(data any) (io.Reader, error) {
var body io.Reader
var j []byte
switch p := data.(type) {
case nil:
body = nil
case string:
j = []byte(p)
body = bytes.NewBuffer(j)
default:
var buf bytes.Buffer
if err := jsonEncode(&buf, data); err != nil {
return nil, errors.Wrap(err, "encoding request payload")
}
body = &buf
}
return body, nil
}