-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
100 lines (84 loc) · 1.99 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
90
91
92
93
94
95
96
97
98
99
100
package trackingmore
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
)
var (
baseUrl string
apiVersion string
)
func init() {
baseUrl = "https://api.trackingmore.com/"
apiVersion = "v4"
}
func (client *Client) sendApiRequest(ctx context.Context, method, path string, queryParams interface{}, inputData interface{}, resultData interface{}) (*Response, error) {
var body io.Reader
if inputData != nil {
jsonData, err := json.Marshal(inputData)
if err != nil {
return nil, err
}
body = bytes.NewBuffer(jsonData)
}
requestUrl := baseUrl + apiVersion + path
req, err := http.NewRequestWithContext(ctx, method, requestUrl, body)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("Tracking-Api-Key", client.apiKey)
if queryParams != nil {
queryString := url.Values{}
if err := addStructParams(queryParams, &queryString); err != nil {
return nil, err
}
req.URL.RawQuery = queryString.Encode()
}
resp, err := client.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody := new(bytes.Buffer)
respBody.ReadFrom(resp.Body)
result := &Response{
Meta: Meta{},
Data: resultData,
}
err = json.Unmarshal([]byte(respBody.String()), result)
if err != nil {
return nil, err
}
return result, nil
}
func addStructParams(params interface{}, values *url.Values) error {
v := url.Values{}
val := reflect.ValueOf(params)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return fmt.Errorf("params must be a struct or a pointer to struct")
}
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
tag := field.Tag.Get("url")
if tag == "" {
tag = field.Name
}
value := val.Field(i).Interface()
if value != reflect.Zero(val.Field(i).Type()).Interface() {
v.Add(tag, fmt.Sprintf("%v", value))
}
}
*values = v
return nil
}