This repository has been archived by the owner on Jul 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
105 lines (93 loc) · 2.34 KB
/
http.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
102
103
104
105
package client
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
const (
httpParamPage = "page"
httpParamPageSize = "pageSize"
headerClientID = "Izanami-Client-Id"
headerClientSecret = "Izanami-Client-Secret"
)
// Metadata represents metadata parts of http response
type Metadata struct {
Page int `json:"page"`
PageSize int `json:"pageSize"`
Count int `json:"count"`
NbPages int `json:"nbPages"`
}
func (c *Client) buildURL(path string, method string, httpParams map[string]string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s", c.apiURL, path)
req, errRequest := http.NewRequest(method, url, body)
if errRequest != nil {
return nil, errRequest
}
if httpParams != nil {
// Add query params
q := req.URL.Query()
for k, v := range httpParams {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set(headerClientID, c.clientID)
req.Header.Set(headerClientSecret, c.clientSecret)
return req, nil
}
func (c *Client) get(path string, httpParams map[string]string) ([]byte, error) {
req, errReq := c.buildURL(path, http.MethodGet, httpParams, nil)
if errReq != nil {
return nil, errReq
}
return c.do(req)
}
func (c *Client) post(path string, body interface{}) ([]byte, error) {
b, errJSON := json.Marshal(body)
if errJSON != nil {
return nil, errJSON
}
req, errReq := c.buildURL(path, http.MethodPost, nil, bytes.NewReader(b))
if errReq != nil {
return nil, errReq
}
return c.do(req)
}
func (c *Client) put(path string, body interface{}) ([]byte, error) {
b, errJSON := json.Marshal(body)
if errJSON != nil {
return nil, errJSON
}
req, errReq := c.buildURL(path, http.MethodPut, nil, bytes.NewReader(b))
if errReq != nil {
return nil, errReq
}
return c.do(req)
}
func (c *Client) delete(path string) error {
req, errReq := c.buildURL(path, http.MethodDelete, nil, nil)
if errReq != nil {
return errReq
}
_, errDo := c.do(req)
return errDo
}
func (c *Client) do(req *http.Request) ([]byte, error) {
res, errDo := c.HttpClient.Do(req)
if errDo != nil {
return nil, errDo
}
defer res.Body.Close()
body, errRead := ioutil.ReadAll(res.Body)
if errRead != nil {
return nil, errRead
}
if res.StatusCode >= 400 {
return nil, fmt.Errorf("[%d] %s", res.StatusCode, string(body))
}
return body, nil
}