-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
92 lines (76 loc) · 2.01 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
package subclub
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func (c *Client) get(path string, r interface{}) (interface{}, error) {
return c.request(http.MethodGet, path, nil, r)
}
func (c *Client) post(path string, data, r interface{}) (interface{}, error) {
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(data)
return c.request(http.MethodPost, path, b, r)
}
func (c *Client) put(path string, data, r interface{}) (interface{}, error) {
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(data)
return c.request(http.MethodPut, path, b, r)
}
func (c *Client) delete(path string, data map[string]string) (interface{}, error) {
r, err := c.buildRequest(http.MethodDelete, path, nil)
if err != nil {
return nil, err
}
q := r.URL.Query()
for k, v := range data {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
return c.doRequest(r, nil)
}
func (c *Client) request(method, path string, data io.Reader, result interface{}) (interface{}, error) {
r, err := c.buildRequest(method, path, data)
if err != nil {
return nil, err
}
return c.doRequest(r, result)
}
func (c *Client) buildRequest(method, path string, data io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s", c.Config.BaseURL, path)
r, err := http.NewRequest(method, url, data)
if err != nil {
return nil, fmt.Errorf("Create request: %v", err)
}
c.prepareRequest(r)
return r, nil
}
func (c *Client) doRequest(r *http.Request, result interface{}) (interface{}, error) {
resp, err := c.Client.Do(r)
if err != nil {
return nil, fmt.Errorf("Request: %v", err)
}
defer resp.Body.Close()
var env interface{}
if result != nil {
env = result
err = json.NewDecoder(resp.Body).Decode(&env)
if err != nil {
return nil, err
}
}
return env, nil
}
func (c *Client) prepareRequest(r *http.Request) {
ua := c.Config.UserAgent
if ua == "" {
ua = "go-subclub"
}
r.Header.Set("User-Agent", ua)
r.Header.Add("Content-Type", "application/json")
if c.APIKey != "" {
r.Header.Add("Authorization", "Bearer "+c.APIKey)
}
}