forked from yoppi/go-chatwork
/
client.go
203 lines (164 loc) · 4.66 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package gochatwork
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"strconv"
"strings"
)
// HTTP interface of HTTP METHODS's methods
type HTTP interface {
Get()
Post()
Put()
Delete()
}
// ChatWorkError is error model
type ChatWorkError struct {
Errors []string `json:"errors"`
}
// error returns Errors
func (e *ChatWorkError) error() error {
if len(e.Errors) == 0 {
return nil
}
return errors.New(strings.Join(e.Errors, ", "))
}
// Client ChatWork HTTP client
type Client struct {
APIKey string
BaseURL string
HTTP
HTTPClient *http.Client
latestRateLimit *RateLimit
}
// NewClient returns ChatWork HTTP Client
func NewClient(apiKey string) *Client {
return &Client{APIKey: apiKey, BaseURL: BaseURL}
}
// Get GET method
func (c *Client) Get(endpoint string, params map[string]string) ([]byte, error) {
return c.execute(http.MethodGet, endpoint, params)
}
// Post POST method
func (c *Client) Post(endpoint string, params map[string]string) ([]byte, error) {
return c.execute(http.MethodPost, endpoint, params)
}
// Put PUT method
func (c *Client) Put(endpoint string, params map[string]string) ([]byte, error) {
return c.execute(http.MethodPut, endpoint, params)
}
// Delete DELETE method
func (c *Client) Delete(endpoint string, params map[string]string) ([]byte, error) {
return c.execute(http.MethodDelete, endpoint, params)
}
func (c *Client) postFile(endpoint string, message, fileName string, file io.Reader) ([]byte, error) {
req, err := c.fileUploadRequest(endpoint, message, fileName, file)
if err != nil {
return nil, err
}
return c.sendRequest(req)
}
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, error) {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
return []byte(``), err
}
if resp.StatusCode == http.StatusNoContent {
return []byte(``), nil
}
if resp.StatusCode != http.StatusOK {
var er ChatWorkError
if err := json.Unmarshal(body, &er); err != nil {
// create a slice for the errors
var errStrs []string
errStrs = append(errStrs, err.Error())
errStrs = append(errStrs, bytes.NewBuffer(body).String())
return []byte(``), fmt.Errorf(strings.Join(errStrs, "\n"))
}
return []byte(``), er.error()
}
return body, nil
}
func (c *Client) fileUploadRequest(endpoint, message, fileName string, file io.Reader) (*http.Request, error) {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
w.WriteField("message", html.EscapeString(message))
fw, err := w.CreateFormFile("file", fileName)
if err != nil {
return nil, err
}
if _, err = io.Copy(fw, file); err != nil {
return nil, err
}
w.Close()
req, err := http.NewRequest(http.MethodPost, c.BaseURL+endpoint, &buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Add("X-ChatWorkToken", c.APIKey)
return req, nil
}
func (c *Client) request(method, endpoint string, params map[string]string) *http.Request {
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)
return req
}
func (c *Client) sendRequest(req *http.Request) ([]byte, error) {
if c.HTTPClient == nil {
c.HTTPClient = &http.Client{}
}
resp, err := c.HTTPClient.Do(req)
c.latestRateLimit = c.rateLimit(resp)
if err != nil {
return []byte(``), err
}
return c.parseBody(resp)
}
func (c *Client) execute(method, endpoint string, params map[string]string) ([]byte, error) {
req := c.request(method, endpoint, params)
return c.sendRequest(req)
}
func (c *Client) rateLimit(resp *http.Response) *RateLimit {
limit, _ := strconv.Atoi(resp.Header.Get("X-RateLimit-Limit"))
remaining, _ := strconv.Atoi(resp.Header.Get("X-RateLimit-Remaining"))
resetTime, _ := strconv.ParseInt(resp.Header.Get("X-RateLimit-Reset"), 10, 64)
return &RateLimit{Limit: limit, Remaining: remaining, ResetTime: resetTime}
}