/
client.go
268 lines (210 loc) · 6.07 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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package esign
import (
"bytes"
"context"
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/tidwall/gjson"
"github.com/shenghui0779/sdk-go/lib"
"github.com/shenghui0779/sdk-go/lib/curl"
)
// Client E签宝客户端
type Client struct {
host string
appid string
secret string
httpCli curl.Client
logger func(ctx context.Context, data map[string]string)
}
func (c *Client) url(path string, query url.Values) string {
var builder strings.Builder
builder.WriteString(c.host)
if len(path) != 0 && path[0] != '/' {
builder.WriteString("/")
}
builder.WriteString(path)
if len(query) != 0 {
builder.WriteString("?")
builder.WriteString(query.Encode())
}
return builder.String()
}
func (c *Client) do(ctx context.Context, method, path string, query url.Values, params lib.X) (gjson.Result, error) {
reqURL := c.url(path, query)
log := lib.NewReqLog(method, reqURL)
defer log.Do(ctx, c.logger)
header := http.Header{}
header.Set(curl.HeaderAccept, AcceptAll)
header.Set(HeaderTSignOpenAppID, c.appid)
header.Set(HeaderTSignOpenAuthMode, AuthModeSign)
header.Set(HeaderTSignOpenCaTimestamp, strconv.FormatInt(time.Now().UnixMilli(), 10))
var (
body []byte
err error
)
options := make([]SignOption, 0)
if len(query) != 0 {
options = append(options, WithSignValues(query))
}
if params != nil {
body, err = json.Marshal(params)
if err != nil {
return lib.Fail(err)
}
log.SetReqBody(string(body))
contentMD5 := ContentMD5(body)
header.Set(curl.HeaderContentType, "application/json; charset=UTF-8")
header.Set(HeaderContentMD5, contentMD5)
options = append(options, WithSignContMD5(contentMD5), WithSignContType("application/json; charset=UTF-8"))
}
header.Set(HeaderTSignOpenCaSignature, NewSigner(method, path, options...).Do(c.secret))
log.SetReqHeader(header)
resp, err := c.httpCli.Do(ctx, method, reqURL, body, lib.HeaderToHttpOption(header)...)
if err != nil {
return lib.Fail(err)
}
defer resp.Body.Close()
log.SetRespHeader(resp.Header)
log.SetStatusCode(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return lib.Fail(fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode))
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return lib.Fail(err)
}
log.SetRespBody(string(b))
ret := gjson.ParseBytes(b)
if code := ret.Get("code").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("message")))
}
return ret.Get("data"), nil
}
func (c *Client) doStream(ctx context.Context, uploadURL string, reader io.ReadSeeker) error {
log := lib.NewReqLog(http.MethodPut, uploadURL)
defer log.Do(ctx, c.logger)
h := md5.New()
if _, err := io.Copy(h, reader); err != nil {
return err
}
header := http.Header{}
header.Set(curl.HeaderContentType, curl.ContentStream)
header.Set(HeaderContentMD5, base64.StdEncoding.EncodeToString(h.Sum(nil)))
log.SetReqHeader(header)
// 文件指针移动到头部
if _, err := reader.Seek(0, 0); err != nil {
return err
}
buf := bytes.NewBuffer(make([]byte, 0, 20<<10)) // 20kb
if _, err := io.Copy(buf, reader); err != nil {
return err
}
resp, err := c.httpCli.Do(ctx, http.MethodPut, uploadURL, buf.Bytes(), lib.HeaderToHttpOption(header)...)
if err != nil {
return err
}
defer resp.Body.Close()
log.SetStatusCode(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
log.SetRespBody(string(b))
ret := gjson.ParseBytes(b)
if code := ret.Get("errCode").Int(); code != 0 {
return fmt.Errorf("%d | %s", code, ret.Get("msg"))
}
return nil
}
// GetJSON GET请求JSON数据
func (c *Client) GetJSON(ctx context.Context, path string, query url.Values) (gjson.Result, error) {
return c.do(ctx, http.MethodGet, path, query, nil)
}
// PostJSON POST请求JSON数据
func (c *Client) PostJSON(ctx context.Context, path string, params lib.X) (gjson.Result, error) {
return c.do(ctx, http.MethodPost, path, nil, params)
}
// PutStream 上传文件流
func (c *Client) PutStream(ctx context.Context, uploadURL string, reader io.ReadSeeker) error {
return c.doStream(ctx, uploadURL, reader)
}
// PutStreamFromFile 通过文件上传文件流
func (c *Client) PutStreamFromFile(ctx context.Context, uploadURL, filename string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
return c.doStream(ctx, uploadURL, f)
}
// Verify 签名验证 (回调通知等)
func (c *Client) Verify(header http.Header, body []byte) error {
appid := header.Get(HeaderTSignOpenAppID)
timestamp := header.Get(HeaderTSignOpenTimestamp)
sign := header.Get(HeaderTSignOpenSignature)
if appid != c.appid {
return fmt.Errorf("appid mismatch, expect = %s, actual = %s", c.appid, appid)
}
h := hmac.New(sha256.New, []byte(c.secret))
h.Write([]byte(timestamp))
h.Write(body)
if v := hex.EncodeToString(h.Sum(nil)); v != sign {
return fmt.Errorf("signature mismatch, expect = %s, actual = %s", v, sign)
}
return nil
}
// Option 自定义设置项
type Option func(c *Client)
// WithHttpCli 设置自定义 HTTP Client
func WithHttpCli(cli *http.Client) Option {
return func(c *Client) {
c.httpCli = curl.NewHTTPClient(cli)
}
}
// WithLogger 设置日志记录
func WithLogger(fn func(ctx context.Context, data map[string]string)) Option {
return func(c *Client) {
c.logger = fn
}
}
// NewClient 返回E签宝客户端
func NewClient(appid, secret string, options ...Option) *Client {
c := &Client{
host: "https://openapi.esign.cn",
appid: appid,
secret: secret,
httpCli: curl.NewDefaultClient(),
}
for _, fn := range options {
fn(c)
}
return c
}
// NewSandbox 返回E签宝「沙箱环境」客户端
func NewSandbox(appid, secret string, options ...Option) *Client {
c := &Client{
host: "https://smlopenapi.esign.cn",
appid: appid,
secret: secret,
httpCli: curl.NewDefaultClient(),
}
for _, fn := range options {
fn(c)
}
return c
}