-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
64 lines (53 loc) · 1.19 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package httpclient
import (
"context"
"io"
"net/http"
goquery "github.com/google/go-querystring/query"
)
const contentTypeKey = "Content-Type"
func (c *client) buildHttpRequest(ctx context.Context, url, method string,
reqOpt requestOption) (*http.Request, error) {
var (
body io.Reader
contentType string
err error
)
if reqOpt.bodyProvider != nil {
body, contentType, err = reqOpt.bodyProvider.Provide()
if err != nil {
return nil, err
}
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
// set header
req.Header = c.header.Clone() // client header
addHeaders(req, reqOpt.header) // request header
if len(contentType) > 0 {
req.Header.Set(contentTypeKey, contentType)
}
// set query
err = setQuery(req, reqOpt.query)
if err != nil {
return nil, err
}
return req, nil
}
func setQuery(req *http.Request, query interface{}) error {
v, err := goquery.Values(query)
if err != nil {
return err
}
req.URL.RawQuery = v.Encode()
return nil
}
func addHeaders(req *http.Request, header http.Header) {
for key, values := range header {
for _, value := range values {
req.Header.Add(key, value)
}
}
}