-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
100 lines (79 loc) · 2.1 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
package oauth
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
"github.com/haozibi/fanfou-sdk-golang/utils"
"github.com/pkg/errors"
)
// RoundTripper Custom RoundTripper
type RoundTripper struct {
debug bool
oauth *OAuth
token *AccessToken
}
// BuildClient build client with oauth
func (o *OAuth) BuildClient(accessToken *AccessToken) *http.Client {
return &http.Client{
Transport: &RoundTripper{
debug: utils.IsDebug(),
oauth: o,
token: accessToken,
},
}
}
// RoundTrip RoundTrip
func (r *RoundTripper) RoundTrip(userRequest *http.Request) (*http.Response, error) {
params := r.oauth.baseParams()
oauthParams := params
if r.token != nil && len(r.token.Token) > 0 {
params.Set(TOKEN_PARAM, r.token.Token)
oauthParams.Set(TOKEN_PARAM, r.token.Token)
}
otherParams, err := collectParameters(userRequest)
if err != nil {
return nil, err
}
for key := range otherParams {
params.Set(key, otherParams.Get(key))
}
bs := baseString(userRequest.Method, canonicalizeURL(userRequest.URL), params)
signature := r.oauth.hmacSha1(r.token.Secret, bs)
if r.debug {
utils.ShowInfomation("Fanfou Signed BaseString", bs)
}
oauthParams.Set(SIGNATURE_PARAM, signature)
userRequest.Header.Set("Authorization", authHeaderValue(oauthParams))
if r.debug {
utils.ShowInfomation("Fanfou Signed Request", userRequest)
}
return r.oauth.client.Do(userRequest)
}
func collectParameters(req *http.Request) (url.Values, error) {
params := url.Values{}
query := req.URL.Query()
for key := range query {
params.Set(key, query.Get(key))
}
if req.Body != nil &&
req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
b, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, errors.WithStack(err)
}
values, err := url.ParseQuery(string(b))
if err != nil {
return nil, errors.WithStack(err)
}
for key := range values {
params.Set(key, values.Get(key))
}
req.Body = ioutil.NopCloser(bytes.NewReader(b))
}
return params, nil
}
func authHeaderValue(params url.Values) string {
paramsString := sortValue(params, `%s="%s"`)
return "OAuth " + paramsString
}