-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
179 lines (158 loc) · 3.98 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
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
package w7
import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"github.com/go-resty/resty/v2"
"github.com/w7corp/sdk-open-cloud-go/service"
"golang.org/x/net/publicsuffix"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"sort"
"strconv"
"time"
)
type Option struct {
ApiUrl string
Debug bool
}
func NewClient(appId string, appSecret string, options ...Option) *Client {
client := &Client{
appId: appId,
appSecret: appSecret,
}
client.log = &wlog{}
client.apiUrl = "https://api.w7.cc"
for _, option := range options {
if option.ApiUrl != "" {
client.apiUrl = option.ApiUrl
}
if option.Debug {
client.log.debug = option.Debug
}
}
cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
httpClient := resty.NewWithClient(&http.Client{
Timeout: 30 * time.Second,
Jar: cookieJar,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 1000,
MaxIdleConnsPerHost: math.MaxInt,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
})
httpClient.SetRetryCount(3)
httpClient.SetBaseURL(client.apiUrl)
httpClient.OnBeforeRequest(client.makeSign)
httpClient.OnAfterResponse(client.onafterResponse)
client.SetHttpClient(httpClient)
client.OauthService = &service.OauthService{
HttpClient: httpClient,
}
return client
}
type Client struct {
apiUrl string
appId string
appSecret string
log *wlog
httpClient *resty.Client
OauthService *service.OauthService
}
func (c *Client) SetHttpClient(client *resty.Client) {
c.httpClient = client
}
func (c *Client) GetHttpClient() *resty.Client {
return c.httpClient
}
func (c *Client) makeSign(client *resty.Client, request *resty.Request) error {
var sign [16]byte
if request.Body != nil && resty.DetectContentType(request.Body) == "application/json" {
body, ok := request.Body.(map[string]interface{})
if !ok {
return errors.New("request property body must be ")
}
body["appid"] = c.appId
body["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
body["nonce"] = c.getRandomString(16)
signByte, err := client.JSONMarshal(body)
if err != nil {
return err
}
signStr := string(signByte)
signStr += c.appSecret
sign = md5.Sum([]byte(signStr))
body["sign"] = hex.EncodeToString(sign[:])
request.SetBody(body)
} else {
request.SetFormData(map[string]string{
"appid": c.appId,
"timestamp": strconv.FormatInt(time.Now().Unix(), 10),
"nonce": c.getRandomString(16),
})
var keys []string
signStr := ""
for s, _ := range request.FormData {
if s == "sign" {
continue
}
keys = append(keys, s)
}
sort.Strings(keys)
for i, k := range keys {
signStr += fmt.Sprintf("%s=%s", k, url.QueryEscape(request.FormData.Get(k)))
if i < len(keys)-1 {
signStr += "&"
}
}
signStr += c.appSecret
c.log.Printf("签名数据:%s \n", signStr)
sign = md5.Sum([]byte(signStr))
request.SetFormData(map[string]string{
"sign": hex.EncodeToString(sign[:]),
})
}
c.log.Printf("签名:%s \n", hex.EncodeToString(sign[:]))
return nil
}
func (c *Client) onafterResponse(client *resty.Client, response *resty.Response) error {
c.log.Println("response data: " + string(response.Body()))
return nil
}
func (c *Client) getRandomString(n int) string {
str := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"
bytes := []byte(str)
var result []byte
for i := 0; i < n; i++ {
result = append(result, bytes[rand.Intn(len(bytes))])
}
return string(result)
}
type wlog struct {
debug bool
}
func (self *wlog) Println(v ...any) {
if self.debug {
log.Println(v...)
}
}
func (self *wlog) Printf(format string, v ...any) {
if self.debug {
log.Printf(format, v...)
}
}