-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathrequest.go
62 lines (57 loc) · 1.48 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
package chargebee
import (
"bytes"
"io"
"net/url"
"strings"
)
func (request RequestObj) Request() (*Result, error) {
result, err := request.RequestWithEnv(DefaultConfig())
return result, err
}
func (request RequestObj) RequestWithEnv(env Environment) (*Result, error) {
var body io.Reader
var path string
if request.isJsonRequest {
path, body = getJsonBody(request.Method, request.Path, request.JsonBody)
} else {
path, body = getBody(request.Method, request.Path, request.Params)
}
req, err := newRequest(env, request.Method, path, body, request.Header, request.subDomain, request.isJsonRequest)
if err != nil {
panic(err)
}
if request.Context != nil {
req = req.WithContext(request.Context)
}
res, requestError := Do(req)
result := &Result{}
if requestError != nil {
return result, requestError
}
if err := UnmarshalJSON(res.Body, result); err != nil {
return result, nil
}
result.responseHeaders = res.Headers
result.httpStatusCode = res.StatusCode
return result, requestError
}
func getBody(method string, path string, form *url.Values) (string, io.Reader) {
var body io.Reader
if form != nil && len(*form) > 0 {
data := form.Encode()
if strings.ToUpper(method) == "GET" {
path += "?" + data
} else {
body = bytes.NewBufferString(data)
}
}
return path, body
}
func getJsonBody(method string, path string, jsonBody string) (string, io.Reader) {
var body io.Reader
if jsonBody != "" {
body = bytes.NewBufferString(jsonBody)
}
return path, body
}