-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcalendly.go
94 lines (76 loc) · 1.88 KB
/
calendly.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
package calendly
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
// CalendlyWrapper holds the main Calendly client
type CalendlyWrapper struct {
apiKey string
baseApiUrl string
customHeaders map[string]string
}
// CalendlyWrapperInput is used as input for the New function
type CalendlyWrapperInput struct {
ApiKey string
BaseApiUrl string
CustomHeaders map[string]string
}
// New returns a CalendlyWrapper to be used
func New(input *CalendlyWrapperInput) *CalendlyWrapper {
var baseApiUrl string
if input.BaseApiUrl != "" {
baseApiUrl = input.BaseApiUrl
} else {
baseApiUrl = "https://api.calendly.com/"
}
cw := &CalendlyWrapper{
apiKey: input.ApiKey,
baseApiUrl: baseApiUrl,
customHeaders: input.CustomHeaders,
}
return cw
}
func (cw *CalendlyWrapper) sendGetReq(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := cw.sendRawReq(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (cw *CalendlyWrapper) sendPostReq(url string, payload []byte) ([]byte, error) {
req, err := http.NewRequest("POST", url, bytes.NewReader(payload))
if err != nil {
return nil, err
}
resp, err := cw.sendRawReq(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (cw *CalendlyWrapper) sendRawReq(req *http.Request) ([]byte, error) {
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", cw.apiKey))
for key, value := range cw.customHeaders {
req.Header.Add(key, value)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 && resp.StatusCode != 201 {
return nil, fmt.Errorf("status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return body, nil
}