-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathclient.go
98 lines (81 loc) · 2.05 KB
/
client.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 gochatwork
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
type Http interface {
Get()
Post()
Put()
Delete()
}
type Client struct {
ApiKey string
BaseUrl string
Http
}
func NewClient(apiKey string) *Client {
return &Client{ApiKey: apiKey, BaseUrl: BaseUrl}
}
func (c *Client) Get(endpoint string, params map[string]string) []byte {
return c.execute("GET", endpoint, params)
}
func (c *Client) Post(endpoint string, params map[string]string) []byte {
return c.execute("POST", endpoint, params)
}
func (c *Client) Put(endpoint string, params map[string]string) []byte {
return c.execute("PUT", endpoint, params)
}
func (c *Client) Delete(endpoint string, params map[string]string) []byte {
return c.execute("DELETE", endpoint, params)
}
func (c *Client) buildUrl(baseUrl, endpoint string, params map[string]string) string {
query := make([]string, len(params))
for k := range params {
query = append(query, k+"="+params[k])
}
return baseUrl + endpoint + "?" + strings.Join(query, "&")
}
func (c *Client) buildBody(params map[string]string) url.Values {
body := url.Values{}
for k := range params {
body.Add(k, params[k])
}
return body
}
func (c *Client) parseBody(resp *http.Response) []byte {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
return []byte(``)
}
return body
}
func (c *Client) execute(method, endpoint string, params map[string]string) []byte {
httpClient := &http.Client{}
var (
req *http.Request
requestErr error
)
if method != "GET" {
req, requestErr = http.NewRequest(method, c.BaseUrl+endpoint, bytes.NewBufferString(c.buildBody(params).Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
} else {
req, requestErr = http.NewRequest(method, c.buildUrl(c.BaseUrl, endpoint, params), nil)
}
if requestErr != nil {
panic(requestErr)
}
req.Header.Add("X-ChatWorkToken", c.ApiKey)
resp, err := httpClient.Do(req)
if err != nil {
log.Println(err)
return []byte(``)
}
return c.parseBody(resp)
}