-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhellosign.go
333 lines (303 loc) · 7.89 KB
/
hellosign.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2016 Precisely AB.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package hellosign
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"strconv"
"io"
"github.com/ajg/form"
)
const (
baseURL string = "https://api.hellosign.com/v3"
contentType = "content-type"
xRatelimitLimit = "x-Ratelimit-Limit"
xRatelimitLimitRemaining = "x-Ratelimit-Limit-Remaining"
xRateLimitReset = "x-Ratelimit-Reset"
)
// ListInfo struct with properties for all list epts.
type ListInfo struct {
Page uint64 `json:"page"`
NumPages uint64 `json:"num_pages"`
NumResults uint64 `json:"num_results"`
PageSize uint64 `json:"page_size"`
}
// ListParms struct with options for performing list operations.
type ListParms struct {
AccountID string `form:"account_id,omitempty"`
Page uint64 `form:"page,omitempty"`
PageSize uint64 `form:"page_size,omitempty"`
Query string `form:"query,omitempty"`
}
// FormField a field where some kind of action needs to be taken.
type FormField struct {
APIID string `json:"api_id"`
Name string `json:"name"`
Type string `json:"type"`
X uint64 `json:"x"`
Y uint64 `json:"y"`
Width uint64 `json:"width"`
Height uint64 `json:"height"`
Required bool `json:"required"`
}
// APIErr an error returned from the Hellosign API.
type APIErr struct {
Code int // HTTP response code
Message string
Name string
}
// APIWarn a list of warnings returned from the HelloSign API.
type APIWarn struct {
Code int // HTTP response code
Warnings []struct {
Message string
Name string
}
}
func (a APIErr) Error() string {
return fmt.Sprintf("%s: %s", a.Name, a.Message)
}
func (a APIWarn) Error() string {
outMsg := ""
for _, w := range a.Warnings {
outMsg += fmt.Sprintf("%s: %s\n", w.Name, w.Message)
}
return outMsg
}
type hellosign struct {
apiKey string
RateLimit uint64 // Number of requests allowed per hour
RateLimitRemaining uint64 // Remaining number of requests this hour
RateLimitReset uint64 // When the limit will be reset. In seconds from epoch
LastStatusCode int
}
// Initializes a new Hellosign API client.
func newHellosign(apiKey string) *hellosign {
return &hellosign{
apiKey: apiKey,
}
}
func DumpRequest(req *http.Request) {
d, err := httputil.DumpRequest(req, true)
if err == nil {
fmt.Println(string(d))
}
}
func (c *hellosign) perform(req *http.Request) (*http.Response, error) {
req.Header.Add("accept", "application/json")
req.SetBasicAuth(c.apiKey, "")
//DumpRequest(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
c.LastStatusCode = resp.StatusCode
if resp.StatusCode >= 400 {
return nil, c.parseResponseError(resp)
}
for _, hk := range []string{xRatelimitLimit, xRatelimitLimitRemaining, xRateLimitReset} {
hv := resp.Header.Get(hk)
if hv == "" {
continue
}
hvui, pErr := strconv.ParseUint(hv, 10, 64)
if pErr != nil {
continue
}
switch hk {
case xRatelimitLimit:
c.RateLimit = hvui
case xRatelimitLimitRemaining:
c.RateLimitRemaining = hvui
case xRateLimitReset:
c.RateLimitReset = hvui
}
}
return resp, err
}
func (c *hellosign) parseResponseError(resp *http.Response) error {
e := &struct {
Err struct {
Msg *string `json:"error_msg"`
Name *string `json:"error_name"`
} `json:"error"`
}{}
w := &struct {
Warnings []struct {
Msg *string `json:"warning_msg"`
Name *string `json:"warning_name"`
} `json:"warnings"`
}{}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(b, e)
if err != nil {
return err
}
if e.Err.Name != nil {
return APIErr{Code: resp.StatusCode, Message: *e.Err.Msg, Name: *e.Err.Name}
}
err = json.Unmarshal(b, w)
if err != nil {
return err
}
if len(w.Warnings) == 0 {
return errors.New("Could not parse response error or warning")
}
retErr := APIWarn{}
warns := []struct {
Name string
Message string
}{}
for _, w := range w.Warnings {
warns = append(warns, struct {
Name string
Message string
}{
Name: *w.Name,
Message: *w.Msg,
})
}
return retErr
}
func (c *hellosign) parseResponse(resp *http.Response, dst interface{}) error {
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
d := json.NewDecoder(resp.Body)
d.UseNumber()
return d.Decode(dst)
}
return errors.New("Status code invalid")
}
func (c *hellosign) post(ept string, headers *map[string]string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPost, c.getEptURL(ept), body)
if err != nil {
return nil, err
}
if headers != nil {
for k, v := range *headers {
req.Header.Add(k, v)
}
}
return c.perform(req)
}
func (c *hellosign) postForm(ept string, o interface{}) (*http.Response, error) {
b, w, err := c.marshalMultipart(o)
if err != nil {
return nil, err
}
return c.post(ept, &map[string]string{
contentType: w.FormDataContentType(),
}, b)
}
func (c *hellosign) postFormAndParse(ept string, inp, dst interface{}) (err error) {
resp, err := c.postForm(ept, inp)
if err != nil {
return err
}
defer func() { err = resp.Body.Close() }()
return c.parseResponse(resp, dst)
}
func (c *hellosign) postEmptyExpect(ept string, expected int) (ok bool, err error) {
resp, err := c.post(ept, nil, nil)
if err != nil {
return false, err
}
defer func() { err = resp.Body.Close() }()
if resp.StatusCode != expected {
return false, errors.New(resp.Status)
}
return true, nil
}
func (c *hellosign) delete(ept string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodDelete, c.getEptURL(ept), nil)
if err != nil {
return nil, err
}
return c.perform(req)
}
// BoolToInt converts a boolean value to a value appropriate for api interaction.
func BoolToInt(v bool) int8 {
if !v {
return int8(0)
}
return int8(1)
}
// GetEptURL returns the full HelloSign api url for a given endpoint.
func GetEptURL(ept string) string {
return fmt.Sprintf("%s/%s", baseURL, ept)
}
func (c *hellosign) getEptURL(ept string) string {
return GetEptURL(ept)
}
func (c *hellosign) get(ept string, params *string) (*http.Response, error) {
url := c.getEptURL(ept)
if params != nil && *params != "" {
url = fmt.Sprintf("%s?%s", url, *params)
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := c.perform(req)
return resp, err
}
func (c *hellosign) getAndParse(ept string, params *string, dst interface{}) (err error) {
resp, err := c.get(ept, params)
if err != nil {
return err
}
defer func() { err = resp.Body.Close() }()
return c.parseResponse(resp, dst)
}
func (c *hellosign) getFiles(ept, fileType string, getURL bool) (body []byte, fileURL *FileURL, err error) {
if fileType != "" && fileType != "pdf" && fileType != "zip" {
return []byte{}, nil, errors.New("Invalid file type specified, pdf or zip")
}
parms, err := form.EncodeToString(&struct {
FileType string `form:"file_type,omitempty"`
GetURL bool `form:"get_url,omitempty"`
}{
FileType: fileType,
GetURL: getURL,
})
if err != nil {
return []byte{}, nil, err
}
resp, err := c.get(ept, &parms)
if err != nil {
return []byte{}, nil, err
}
defer func() { err = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return []byte{}, nil, errors.New(resp.Status)
}
if getURL {
msg := &FileURL{}
if respErr := c.parseResponse(resp, msg); respErr != nil {
return []byte{}, nil, respErr
}
return []byte{}, msg, nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, nil, err
}
return b, nil, nil
}
func (c *hellosign) list(ept string, parms ListParms, out interface{}) error {
paramString, err := form.EncodeToString(parms)
if err != nil {
return err
}
if err := c.getAndParse(ept, ¶mString, out); err != nil {
return err
}
return nil
}