-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
80 lines (74 loc) · 1.61 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
package requests
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
)
type HTTPOptions struct {
Headers http.Header
Params *url.Values
Body interface{}
}
func (cli *Client) ResolveURL(path string, params *url.Values) *url.URL {
rel := &url.URL{Path: path}
if params != nil {
rel.RawQuery = params.Encode()
}
if cli.Options.BaseURL != nil {
return cli.Options.BaseURL.ResolveReference(rel)
}
return rel
}
func (cli *Client) BuildRequestHeader(h http.Header) http.Header {
header := cli.Options.DefaultHeaders.Clone()
if header == nil {
header = make(http.Header)
}
if len(h) == 0 {
return header
}
for key, values := range h {
for _, value := range values {
header.Add(key, value)
}
}
return header
}
func (cli *Client) NewRequest(ctx context.Context, method, path string, httpOptions *HTTPOptions) (*http.Request, error) {
// build url
url := cli.ResolveURL(path, httpOptions.Params)
// build body reader
reader, err := BuildReaderFromBody(httpOptions.Body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, method, url.String(), reader)
if err != nil {
return nil, err
}
// build request header
headers := cli.BuildRequestHeader(httpOptions.Headers)
req.Header = headers
return req, nil
}
func BuildReaderFromBody(body interface{}) (io.Reader, error) {
if body == nil {
return nil, nil
}
var byteData []byte
switch data := body.(type) {
case []byte:
byteData = data
default:
var err error
byteData, err = json.Marshal(body)
if err != nil {
return nil, err
}
}
reader := bytes.NewReader(byteData)
return reader, nil
}