/
request.go
89 lines (72 loc) · 2.44 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
package request
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"github.com/ViBiOh/httputils/pkg/errors"
)
const (
// ContentTypeHeader value
ContentTypeHeader = "Content-Type"
)
// New prepare a request from given params
func New(method string, url string, body io.Reader, headers http.Header) (req *http.Request, err error) {
req, err = http.NewRequest(method, url, body)
if err != nil {
return nil, errors.WithStack(err)
}
req.Header = headers
return
}
// JSON prepare a JSON request from given params
func JSON(method string, url string, body interface{}, headers http.Header) (*http.Request, error) {
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, errors.WithStack(err)
}
if headers == nil {
headers = http.Header{}
}
headers.Set(ContentTypeHeader, "application/json")
return New(method, url, bytes.NewBuffer(jsonBody), headers)
}
// Form prepare a Form request from given params
func Form(method string, url string, data url.Values, headers http.Header) (*http.Request, error) {
if headers == nil {
headers = http.Header{}
}
headers.Set(ContentTypeHeader, "application/x-www-form-urlencoded")
return New(method, url, strings.NewReader(data.Encode()), headers)
}
// Do send given method with given content to URL with optional headers supplied
func Do(ctx context.Context, method string, url string, body io.Reader, headers http.Header) (io.ReadCloser, int, http.Header, error) {
req, err := New(method, url, body, headers)
if err != nil {
return nil, 0, nil, err
}
return DoAndRead(ctx, req)
}
// DoJSON send given method with given interface{} as JSON to URL with optional headers supplied
func DoJSON(ctx context.Context, url string, data interface{}, headers http.Header, method string) (io.ReadCloser, int, http.Header, error) {
req, err := JSON(method, url, data, headers)
if err != nil {
return nil, 0, nil, err
}
return DoAndRead(ctx, req)
}
// PostForm send form via POST with urlencoded data
func PostForm(ctx context.Context, url string, data url.Values, headers http.Header) (io.ReadCloser, int, http.Header, error) {
req, err := Form(http.MethodPost, url, data, headers)
if err != nil {
return nil, 0, nil, err
}
return DoAndRead(ctx, req)
}
// Get send GET request to URL with optional headers supplied
func Get(ctx context.Context, url string, headers http.Header) (io.ReadCloser, int, http.Header, error) {
return Do(ctx, http.MethodGet, url, nil, headers)
}