-
Notifications
You must be signed in to change notification settings - Fork 0
/
npc.go
180 lines (164 loc) · 4.95 KB
/
npc.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
package npc
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
const (
EmptyString = ""
DefaultApiEndpoint = "open.c.163.com"
DefaultApiRegion = "cn-east-1"
)
type Npc struct {
Endpoint string
AccessKey string
SecretKey string
Region string
Verbose bool
}
func DefaultNpc(accessKey string, secretKey string) *Npc {
if accessKey == EmptyString || secretKey == EmptyString {
log.Fatal("accessKey & secretKey can't be empty")
}
return &Npc{Endpoint: DefaultApiEndpoint, AccessKey: accessKey, SecretKey: secretKey, Region: DefaultApiRegion}
}
func NewNpc(endpoint string, accessKey string, secretKey string, region string) *Npc {
if accessKey == EmptyString {
log.Fatal("accessKey can't be empty!")
}
if secretKey == EmptyString {
log.Fatal("secretKey can't be empty!")
}
if endpoint == EmptyString {
log.Fatal("endpoint can't be empty!")
}
if region == EmptyString {
log.Fatal("region can't be empty!")
}
return &Npc{Endpoint: endpoint, AccessKey: accessKey, SecretKey: secretKey, Region: region}
}
func (npc *Npc) setVerbose(verbose bool) {
npc.Verbose = verbose
}
func (npc *Npc) getUrlQueryString(params map[string]string, orderedKeys []string) string {
if params == nil {
return EmptyString
}
v := url.Values{}
switch orderedKeys {
case nil:
for key, value := range params {
v.Add(key, value)
}
default:
for _, key := range orderedKeys {
if value, ok := params[key]; ok {
v.Add(key, value)
}
}
}
return v.Encode()
}
func (npc *Npc) getTimestamp() string {
return time.Now().UTC().Format("2006-01-02T15:04:05Z")
}
func (npc *Npc) getUUID(length int) string {
if length <= 0 {
length = 10
}
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyz"
rand.Seed(time.Now().UnixNano())
b := make([]byte, length)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func (npc *Npc) getHashPayload(requestBody string) string {
hash := sha256.New()
hash.Write([]byte(requestBody))
bytes := hash.Sum(nil)
return hex.EncodeToString(bytes)
}
func (npc *Npc) getCanonicalizedQueryString(params map[string]string) string {
fixedParams := make(map[string]string, 0)
for key, value := range params {
fixedParams[key] = value
}
fixedParams["AccessKey"] = npc.AccessKey
fixedParams["Timestamp"] = npc.getTimestamp()
fixedParams["SignatureVersion"] = "1.0"
fixedParams["SignatureMethod"] = "HMAC-SHA256"
fixedParams["SignatureNonce"] = npc.getUUID(10)
fixedParams["Region"] = npc.Region
orderedKeys := make([]string, 0)
for key, _ := range fixedParams {
orderedKeys = append(orderedKeys, key)
}
sort.Strings(orderedKeys)
return npc.getUrlQueryString(fixedParams, orderedKeys)
}
func (npc *Npc) getString2Sign(method, endpoint, service, canonicalizedQueryString, hashPayload string) string {
return fmt.Sprintf("%s\n%s\n%s\n%s\n%s", method, endpoint, service, canonicalizedQueryString, hashPayload)
}
func (npc *Npc) getSignature(string2Sign, secretKey string) string {
key := []byte(secretKey)
h := hmac.New(sha256.New, key)
h.Write([]byte(string2Sign))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// example:
// service = /keypair
// params = {Action: ListKeyPair, Version: 2018-02-08}
func (npc *Npc) Get(service string, params map[string]string) (*http.Response, error) {
method := http.MethodGet
canonicalizedQueryString := npc.getCanonicalizedQueryString(params)
string2sign := npc.getString2Sign(method, npc.Endpoint, service, canonicalizedQueryString, npc.getHashPayload(EmptyString))
signature := npc.getSignature(string2sign, npc.SecretKey)
signatureParams := map[string]string{
"Signature": signature,
}
httpUrl := "https://" + npc.Endpoint + service + "?" + canonicalizedQueryString + "&" + npc.getUrlQueryString(signatureParams, nil)
if npc.Verbose {
fmt.Println(httpUrl)
}
client := &http.Client{}
req, err := http.NewRequest(method, httpUrl, nil)
if err != nil {
return nil, err
}
return client.Do(req)
}
// example:
// service = /keypair
// Action = {Action: UploadKeyPair, Version: 2018-02-08}
// body = jsonFormat string
func (npc *Npc) Post(service string, params map[string]string, body string) (*http.Response, error) {
method := http.MethodPost
canonicalizedQueryString := npc.getCanonicalizedQueryString(params)
string2sign := npc.getString2Sign(method, npc.Endpoint, service, canonicalizedQueryString, npc.getHashPayload(body))
signature := npc.getSignature(string2sign, npc.SecretKey)
signatureParams := map[string]string{
"Signature": signature,
}
httpUrl := "https://" + npc.Endpoint + service + "?" + canonicalizedQueryString + "&" + npc.getUrlQueryString(signatureParams, nil)
if npc.Verbose {
fmt.Println(httpUrl)
}
client := &http.Client{}
req, err := http.NewRequest(method, httpUrl, strings.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
return client.Do(req)
}