/
populate.go
101 lines (80 loc) · 2.3 KB
/
populate.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
96
97
98
99
100
101
package rubik
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"strings"
)
func populateRequest(entity interface{}, c *Client) (*Payload, error) {
isEntity := checkIsEntity(entity)
if !isEntity {
panic(errors.New("EntityError: The entity you are passing must extend Entity"))
}
req, err := extract(entity)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
req.cancel = cancel
req.context = ctx
req.client = c.httpClient
req.agent = c.UserAgent
req.base = c.url
return &req, nil
}
func populateParamsAndQuery(req *Payload) (string, error) {
var pathWithParams = req.path
if pathWithParams == "@" {
pathWithParams = ""
} else if !strings.HasPrefix(pathWithParams, "/") {
pathWithParams = "/" + pathWithParams
}
pathWithParams, err := substituteParam(pathWithParams, req.params)
if err != nil {
return "", err
}
var fullURL = req.base + pathWithParams
if len(req.query) > 0 {
fullURL += "?" + req.query.Encode()
}
return fullURL, nil
}
func populateHTTPRequest(req *Payload, fullURL string) (*http.Request, error) {
var err error
var requestBody []byte
var httpRequest *http.Request
if req.json && len(req.body) > 0 {
requestBody, err = json.Marshal(req.body)
httpRequest, err = http.NewRequest(req.requestType, fullURL, bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
httpRequest.Header.Set(Content.Header, Content.JSON)
} else if req.urlencoded && len(req.body) > 0 {
requestBody = []byte(req.body.Encode())
httpRequest, err = http.NewRequest(req.requestType, fullURL, bytes.NewBuffer(requestBody))
httpRequest.Header.Set(Content.Header, Content.URLEncoded)
} else if req.formData && req.formBody.Len() > 0 {
httpRequest, err = http.NewRequest(req.requestType, fullURL, req.formBody)
// httpRequest.Header.Set("Content-Type", "multipart/form-data")
} else {
httpRequest, err = http.NewRequest(req.requestType, fullURL, nil)
}
if err != nil {
return nil, err
}
if len(req.headers) > 0 {
for k, v := range req.headers {
httpRequest.Header.Set(k, v[0])
}
}
httpRequest = httpRequest.WithContext(req.context)
if req.agent == "" {
httpRequest.Header.Set(headerUserAgent, clientAgent)
} else {
httpRequest.Header.Set(headerUserAgent, req.agent)
}
return httpRequest, nil
}