forked from carlosdp/twiliogo
/
client.go
125 lines (95 loc) · 2.41 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
package twiliogo
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
const ROOT = "https://api.twilio.com"
const VERSION = "2010-04-01"
type Client interface {
AccountSid() string
AuthToken() string
RootUrl() string
get(url.Values, string) ([]byte, error)
post(url.Values, string) ([]byte, error)
}
type TwilioClient struct {
accountSid string
authToken string
rootUrl string
}
func NewClient(accountSid, authToken string) *TwilioClient {
rootUrl := "/" + VERSION + "/Accounts/" + accountSid
return &TwilioClient{accountSid, authToken, rootUrl}
}
func (client *TwilioClient) post(values url.Values, uri string) ([]byte, error) {
req, err := http.NewRequest("POST", ROOT+uri, strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
req.SetBasicAuth(client.AccountSid(), client.AuthToken())
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpClient := &http.Client{}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return body, err
}
if res.StatusCode != 200 && res.StatusCode != 201 {
if res.StatusCode == 500 {
return body, Error{"Server Error"}
} else {
twilioError := new(TwilioError)
json.Unmarshal(body, twilioError)
return body, twilioError
}
}
return body, err
}
func (client *TwilioClient) get(queryParams url.Values, uri string) ([]byte, error) {
var params *strings.Reader
if queryParams == nil {
queryParams = url.Values{}
}
params = strings.NewReader(queryParams.Encode())
req, err := http.NewRequest("GET", ROOT+uri, params)
if err != nil {
return nil, err
}
req.SetBasicAuth(client.AccountSid(), client.AuthToken())
httpClient := &http.Client{}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return body, err
}
if res.StatusCode != 200 && res.StatusCode != 201 {
if res.StatusCode == 500 {
return body, Error{"Server Error"}
} else {
twilioError := new(TwilioError)
json.Unmarshal(body, twilioError)
return body, twilioError
}
}
return body, err
}
func (client *TwilioClient) AccountSid() string {
return client.accountSid
}
func (client *TwilioClient) AuthToken() string {
return client.authToken
}
func (client *TwilioClient) RootUrl() string {
return client.rootUrl
}