-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
236 lines (188 loc) · 5.1 KB
/
request.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
package tweetgo
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
)
type requestMaker interface {
Do(req *http.Request) (*http.Response, error)
}
type nonceMaker interface {
Generate() string
}
type currentTimer interface {
GetCurrentTime() int64
}
func processParams(input interface{}) url.Values {
v := reflect.ValueOf(input)
params := url.Values{}
for i := 0; i < v.NumField(); i++ {
name := v.Type().Field(i).Tag.Get("schema")
field := v.Field(i)
// Convert to non-pointer version
if field.Kind() == reflect.Ptr {
field = field.Elem()
}
// skip unset/invalid fields
if !field.IsValid() {
continue
}
// get the actual value
value := field.Interface()
if value != nil {
// convert to string based on underlying type
switch value := value.(type) {
case string:
params.Add(name, value)
case bool:
params.Add(name, strconv.FormatBool(value))
case int:
params.Add(name, strconv.FormatInt(int64(value), 10))
case int64:
params.Add(name, strconv.FormatInt(value, 10))
case float64:
params.Add(name, strconv.FormatFloat(value, 'f', -1, 64))
}
}
}
return params
}
func (c Client) executeRequest(method, uri string, params url.Values) (*http.Response, error) {
req, err := c.getSignedRequest(method, uri, params)
if err != nil {
return nil, err
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
b, _ := ioutil.ReadAll(res.Body)
return nil, errors.New("Status: " + res.Status + " - Body: " + string(b))
}
if res.StatusCode != http.StatusOK {
errBody, _ := ioutil.ReadAll(res.Body)
return nil, errors.New(string(errBody))
}
return res, nil
}
func bodyToValues(body io.ReadCloser) (url.Values, error) {
bodyBytes, err := ioutil.ReadAll(body)
if err != nil {
return url.Values{}, err
}
values, err := url.ParseQuery(string(bodyBytes))
if err != nil {
return url.Values{}, err
}
return values, nil
}
func (c Client) getSignedRequest(method, uri string, params url.Values) (*http.Request, error) {
nonce := c.Noncer.Generate()
timestamp := strconv.FormatInt(c.Timer.GetCurrentTime(), 10)
sr := signatureRequest{
method: method,
uri: uri,
nonce: nonce,
timestamp: timestamp,
params: params,
}
oauthSignature, err := c.signature(sr)
if err != nil {
return nil, err
}
hp := headerParameters{
oauthNonce: nonce,
oauthSignature: oauthSignature,
oauthTimestamp: timestamp,
}
authHeader := c.getOauthAuthorizationHeader(hp)
req, err := http.NewRequest(sr.method, sr.uri, strings.NewReader(sr.params.Encode()))
if method == http.MethodGet {
u, err := url.Parse(sr.uri)
if err != nil {
return nil, err
}
u.RawQuery = sr.params.Encode()
req, err = http.NewRequest(sr.method, u.String(), nil)
if err != nil {
return nil, err
}
}
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", authHeader)
return req, nil
}
type signatureRequest struct {
method string
uri string
nonce string
timestamp string
params url.Values
}
func (c Client) signature(sr signatureRequest) (string, error) {
uri, err := url.Parse(sr.uri)
if err != nil {
return "", err
}
values := uri.Query()
values.Add("oauth_consumer_key", c.OAuthConsumerKey)
values.Add("oauth_nonce", sr.nonce)
values.Add("oauth_signature_method", "HMAC-SHA1")
values.Add("oauth_timestamp", sr.timestamp)
values.Add("oauth_version", "1.0")
if c.OAuthAccessToken != "" {
values.Add("oauth_token", c.OAuthAccessToken)
}
for k := range sr.params {
values.Add(url.QueryEscape(k), sr.params.Get(k))
}
parameterString := strings.ReplaceAll(values.Encode(), "+", "%20")
signatureBaseString := strings.ToUpper(sr.method) +
"&" + url.QueryEscape(strings.Split(sr.uri, "?")[0]) +
"&" + url.QueryEscape(parameterString)
signingKey := url.QueryEscape(c.OAuthConsumerSecret) + "&" + url.QueryEscape(c.OAuthAccessTokenSecret)
sig, err := calculateSignature(signatureBaseString, signingKey)
if err != nil {
return "", err
}
return sig, nil
}
func calculateSignature(base, key string) (string, error) {
hash := hmac.New(sha1.New, []byte(key))
_, err := hash.Write([]byte(base))
if err != nil {
return "", err
}
signature := hash.Sum(nil)
return base64.StdEncoding.EncodeToString(signature), nil
}
type headerParameters struct {
oauthNonce string
oauthSignature string
oauthTimestamp string
}
func (c Client) getOauthAuthorizationHeader(p headerParameters) string {
authHeader := "OAuth " +
"oauth_consumer_key=\"" + url.QueryEscape(c.OAuthConsumerKey) + "\", " +
"oauth_nonce=\"" + url.QueryEscape(p.oauthNonce) + "\", " +
"oauth_signature=\"" + url.QueryEscape(p.oauthSignature) + "\", " +
"oauth_signature_method=\"HMAC-SHA1\", " +
"oauth_timestamp=\"" + url.QueryEscape(p.oauthTimestamp) + "\", "
if c.OAuthAccessToken != "" {
authHeader += "oauth_token=\"" + url.QueryEscape(c.OAuthAccessToken) + "\", "
}
authHeader += "oauth_version=\"1.0\""
return authHeader
}