-
Notifications
You must be signed in to change notification settings - Fork 0
/
methods.go
98 lines (74 loc) · 2.19 KB
/
methods.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
package zoop
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
)
const baseUrl = "https://api.zoop.ws/v1/"
// Map data por post in the request
type Params map[string]interface{}
// Map extra request headers
type Headers map[string]string
// Make request and return the response
func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {
// init vars
var url = baseUrl + path
// init an empty payload
payload := strings.NewReader("")
// check for params
if params != nil {
// marshal params
b, err := json.Marshal(params)
if err != nil {
return err
}
// set payload with params
payload = strings.NewReader(string(b))
}
// set request
request, _ := http.NewRequest(method, url, payload)
request.Header.Add("Authorization", c.BasicAuth)
request.Header.Add("accept", "application/json")
request.Header.Add("content-type", "application/json")
// add extra headers
if headers != nil {
for key, value := range headers {
request.Header.Add(key, value)
}
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
// read response
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
// init zoop error response
er := &ErrResponse{}
// check for error message
if err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {
return er.ErrObject
}
// parse data
return json.Unmarshal(data, model)
}
// Execute GET requests
func (c *Client) Get(path string, params interface{}, headers Headers, model interface{}) error {
return c.execute("GET", path, params, headers, model)
}
// Execute POST requests
func (c *Client) Post(path string, params interface{}, headers Headers, model interface{}) error {
return c.execute("POST", path, params, headers, model)
}
// Execute PUT requests
func (c *Client) Put(path string, params interface{}, headers Headers, model interface{}) error {
return c.execute("PUT", path, params, headers, model)
}
// Execute DELETE requests
func (c *Client) Delete(path string, params interface{}, headers Headers, model interface{}) error {
return c.execute("DELETE", path, params, headers, model)
}