-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
96 lines (77 loc) · 1.76 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
package dialonce
import (
"bytes"
"encoding/json"
"errors"
"github.com/segmentio/go-env"
"io"
"net/http"
)
var baseURL = env.GetDefault("DIALONCE_BASE_URL", "https://api.dial-once.com/")
// Client represents a Dial Once client.
type Client struct {
Config *ClientConfig
HTTPClient *http.Client
IVR *IVR
}
// ClientConfig ...
type ClientConfig struct {
AccessToken string
BaseURL string
}
// SetAccessToken ...
func (c *Client) SetAccessToken(accessToken string) {
c.Config.AccessToken = accessToken
}
// SetBaseURL ...
func (c *Client) SetBaseURL(baseURL string) {
c.Config.BaseURL = baseURL
}
// NewConfig with the given access token.
func NewConfig(accessToken string) *ClientConfig {
return &ClientConfig{
AccessToken: accessToken,
BaseURL: baseURL,
}
}
// New client.
func New(config *ClientConfig) *Client {
client := &Client{
Config: config,
HTTPClient: http.DefaultClient,
}
client.IVR = &IVR{client}
return client
}
// Init ...
func Init(accessToken string) *Client {
config := NewConfig(accessToken)
return New(config)
}
// call rpc style endpoint.
func (c *Client) call(verb string, path string, in interface{}) (io.ReadCloser, error) {
url := c.Config.BaseURL + path
data := []byte("")
if in != nil {
body, err := json.Marshal(in)
data = body
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(verb, url, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.Config.AccessToken)
req.Header.Set("Content-Type", "application/json")
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode < 400 {
return res.Body, err
}
defer res.Body.Close()
return nil, errors.New(http.StatusText(res.StatusCode))
}