-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathclient.go
150 lines (121 loc) · 3.45 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
// Package client provides internal utilities for the twilio-go client library.
package client
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/twilio/twilio-go/client/form"
)
// Credentials store user authentication credentials.
type Credentials struct {
Username string
Password string
}
func NewCredentials(username string, password string) *Credentials {
return &Credentials{Username: username, Password: password}
}
// Client encapsulates a standard HTTP backend with authorization.
type Client struct {
*Credentials
HTTPClient *http.Client
accountSid string
UserAgentExtensions []string
}
// default http Client should not follow redirects and return the most recent response.
func defaultHTTPClient() *http.Client {
return &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: time.Second * 10,
}
}
func (c *Client) basicAuth() (string, string) {
return c.Credentials.Username, c.Credentials.Password
}
// SetTimeout sets the Timeout for HTTP requests.
func (c *Client) SetTimeout(timeout time.Duration) {
if c.HTTPClient == nil {
c.HTTPClient = defaultHTTPClient()
}
c.HTTPClient.Timeout = timeout
}
const (
keepZeros = true
delimiter = '.'
escapee = '\\'
)
func (c *Client) doWithErr(req *http.Request) (*http.Response, error) {
client := c.HTTPClient
if client == nil {
client = defaultHTTPClient()
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
// Note that 3XX response codes are allowed for fetches
if res.StatusCode < 200 || res.StatusCode >= 400 {
err = &TwilioRestError{}
if decodeErr := json.NewDecoder(res.Body).Decode(err); decodeErr != nil {
err = errors.Wrap(decodeErr, "error decoding the response for an HTTP error code: "+strconv.Itoa(res.StatusCode))
return nil, err
}
return nil, err
}
return res, nil
}
// SendRequest verifies, constructs, and authorizes an HTTP request.
func (c *Client) SendRequest(method string, rawURL string, data url.Values,
headers map[string]interface{}) (*http.Response, error) {
u, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
valueReader := &strings.Reader{}
goVersion := runtime.Version()
if method == http.MethodGet {
if data != nil {
v, _ := form.EncodeToStringWith(data, delimiter, escapee, keepZeros)
regex := regexp.MustCompile(`\.\d+`)
s := regex.ReplaceAllString(v, "")
u.RawQuery = s
}
}
if method == http.MethodPost {
valueReader = strings.NewReader(data.Encode())
}
req, err := http.NewRequest(method, u.String(), valueReader)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.basicAuth())
// E.g. "User-Agent": "twilio-go/1.0.0 (darwin amd64) go/go1.17.8"
userAgent := fmt.Sprintf("twilio-go/%s (%s %s) go/%s", LibraryVersion, runtime.GOOS, runtime.GOARCH, goVersion)
if len(c.UserAgentExtensions) > 0 {
userAgent += " " + strings.Join(c.UserAgentExtensions, " ")
}
req.Header.Add("User-Agent", userAgent)
if method == http.MethodPost {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
}
for k, v := range headers {
req.Header.Add(k, fmt.Sprint(v))
}
return c.doWithErr(req)
}
// SetAccountSid sets the Client's accountSid field
func (c *Client) SetAccountSid(sid string) {
c.accountSid = sid
}
// Returns the Account SID.
func (c *Client) AccountSid() string {
return c.accountSid
}