-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset_cloud.go
114 lines (102 loc) · 2.39 KB
/
asset_cloud.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
package zcy_sdk_go
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
)
const (
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
)
type AssetCloudRequest struct {
// 完整的请求路径 https://platform.assetcloud.org.cn/dev-api/+请求路径
Url string
// 平台获取的 key
Key string
// 平台获取的 secret
Secret string
// POST和PUT请求的body
Body string
// HTTP method
HttpMethod string
}
type AssetCloudResponse struct {
// 状态码
Code int `json:"code"`
// 是否成功
Success bool `json:"success"`
// 承载数据
Data json.RawMessage `json:"data"`
// 返回消息
Msg string `json:"msg"`
}
func Send(cloudRequest *AssetCloudRequest) *AssetCloudResponse {
client := &http.Client{}
bodyBytes := []byte(cloudRequest.Body)
// url拼接时间戳+加签
url := handleRequest(cloudRequest.Url, cloudRequest.Secret)
request, e := http.NewRequest(cloudRequest.HttpMethod, url, bytes.NewBuffer(bodyBytes))
if e != nil {
log.Printf("error new request: %v\n", e)
return nil
}
request.Header.Add("key", cloudRequest.Key)
// POST、PUT采用json传输
if cloudRequest.HttpMethod == "POST" || cloudRequest.HttpMethod == "PUT" {
request.Header.Add("Content-Type", "application/json")
}
// 发起请求
response, e := client.Do(request)
if e != nil {
log.Printf("error send request: %v\n", e)
return nil
}
defer response.Body.Close()
// 读取请求返回结果
respBytes, e := ioutil.ReadAll(response.Body)
if e != nil {
log.Printf("error reading from response: %v\n", e)
return nil
}
resp := AssetCloudResponse{}
e = json.Unmarshal(respBytes, &resp)
if e != nil {
log.Printf("error json unmarshal: %v\n", e)
return nil
}
return &resp
}
func handleRequest(url, secret string) string {
param := ""
timestamp := strconv.Itoa(int(time.Now().UnixNano() / 1e6))
// 拼接时间戳
if strings.Contains(url, "?") {
url += "×tamp=" + timestamp
} else {
url += "?timestamp=" + timestamp
}
if strings.Contains(url, "?") {
param = url[strings.Index(url, "?")+1:]
}
// 加签
sign := hmacUrl(secret, param)
url += "&sign=" + sign
return url
}
// 拼接hmac
func hmacUrl(secret, url string) string {
hash := hmac.New(sha256.New, []byte(secret))
hash.Write([]byte(url))
sha := hex.EncodeToString(hash.Sum(nil))
return string([]byte(sha))
}