-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathschema.go
More file actions
249 lines (224 loc) · 5.46 KB
/
schema.go
File metadata and controls
249 lines (224 loc) · 5.46 KB
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
package alidns
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
)
const defaultRegionID string = "cn-hangzhou"
const addressOfAPI string = "%s://alidns.aliyuncs.com/"
// CredentialInfo implements param of the crediential
type CredentialInfo struct {
// The API Key ID Required by Aliyun's for accessing the Aliyun's API
AccessKeyID string `json:"access_key_id"`
// The API Key Secret Required by Aliyun's for accessing the Aliyun's API
AccessKeySecret string `json:"access_key_secret"`
// Optional for identifing the region of the Aliyun's Service,The default is zh-hangzhou
RegionID string `json:"region_id,omitempty"`
// The Security Token Required If you enabled the Aliyun's STS(SecurityToken) for accessing the Aliyun's API
SecurityToken string `json:"security_token,omitempty"`
}
// aliClientSchema abstructs the alidns.Client
type aliClientSchema struct {
mutex sync.Mutex
APIHost string
headerPairs keyPairs
requestPairs keyPairs
signString string
signPassword string
version int
}
// keyPair implments of K-V struct
type keyPair struct {
Key string
Value string
}
func getClientSchema(cred *CredentialInfo, scheme string) (*aliClientSchema, error) {
if cred.AccessKeyID == "" || cred.AccessKeySecret == "" {
return nil, errors.New("empty AccessKeyID or AccessKeySecret")
}
if len(cred.RegionID) == 0 {
cred.RegionID = defaultRegionID
}
return defaultSchemaV3(cred, scheme)
}
func (c *aliClientSchema) signReq(method string) error {
if c.signPassword == "" || len(c.requestPairs) == 0 {
return errors.New("alidns: AccessKeySecret or Request(includes AccessKeyId) is Misssing")
}
switch c.version {
case 2:
return c.signReqV2(method)
default:
return c.signReqV3(method)
}
}
func (c *aliClientSchema) UpsertHeader(key string, value string) error {
c.mutex.Lock()
var err error
c.headerPairs, err = c.headerPairs.Upsert(key, value)
if err != nil {
c.mutex.Unlock()
return err
}
c.mutex.Unlock()
return nil
}
func (c *aliClientSchema) UpsertRequestBody(key string, value string) error {
c.mutex.Lock()
var err error
c.requestPairs, err = c.requestPairs.Upsert(key, value)
if err != nil {
c.mutex.Unlock()
return err
}
c.mutex.Unlock()
return nil
}
func (c *aliClientSchema) reqMapToStr() string {
c.mutex.Lock()
result := c.requestPairs.UrlEncodedString()
c.mutex.Unlock()
return result
}
func (c *aliClientSchema) SetAction(action string) error {
if len(action) == 0 {
return errors.New("empty action to set")
}
switch c.version {
case 2:
return c.setActionV2(action)
default:
return c.setActionV3(action)
}
}
// HttpRequest generates http.Request from schema
func (c *aliClientSchema) HttpRequest(cxt context.Context, method string) (*http.Request, error) {
if method == "" {
method = http.MethodGet
}
c.signReq(method)
requestUrl := c.APIHost
if method == http.MethodGet {
requestUrl = fmt.Sprintf("%s?%s", requestUrl, c.reqMapToStr())
}
if c.version == 2 {
requestUrl = c.urlV2(requestUrl)
}
var bodyReader io.Reader
if method == http.MethodPost && c.version > 2 {
bodyReader = bytes.NewReader([]byte(c.reqMapToStr()))
}
req, err := http.NewRequestWithContext(cxt, method, requestUrl, bodyReader)
if err != nil {
return &http.Request{}, err
}
req.Header.Set("Accept", "application/json")
if len(c.headerPairs) == 0 {
return req, nil
}
for _, v := range c.headerPairs {
req.Header.Set(v.Key, v.Value)
}
return req, nil
}
func goVer() float64 {
versionString := runtime.Version()
versionString, _ = strings.CutPrefix(versionString, "go")
verStrings := strings.Split(versionString, ".")
var result float64
for i, v := range verStrings {
tmp, _ := strconv.ParseFloat(v, 32)
result = tmp * (1 / math.Pow10(i))
}
return result
}
func percentCode(src string) string {
result := strings.Replace(src, "+", "%20", -1)
result = strings.Replace(result, "*", "%2A", -1)
result = strings.Replace(result, "%7E", "~", -1)
return result
}
func urlEncode(src string) string {
str0 := url.QueryEscape(src)
str0 = percentCode(str0)
if goVer() > 1.20 {
str0 = strings.Replace(str0, "%26", "&", -1)
}
return str0
}
type keyPairs []keyPair
func (p keyPairs) Upsert(key, value string) (keyPairs, error) {
if key == "" || value == "" {
return p, errors.New("key or value is Empty")
}
srcEl := keyPair{Key: key, Value: value}
for i, el := range p {
if srcEl.Key == el.Key {
p[i] = srcEl
return p, nil
}
}
p = append(p, srcEl)
return p, nil
}
func (p keyPairs) SplitToString(pair, pairs string) string {
result := ""
if len(pair) == 0 {
pair = ":"
}
if len(pairs) == 0 {
pairs = ","
}
for _, el := range p {
result += el.Key +
pair +
el.Value +
pairs
}
return strings.TrimSuffix(result, pairs)
}
func (p keyPairs) PercentCodeString() string {
if len(p) == 0 {
return ""
}
var tmp keyPairs
for _, v := range p {
tmp, _ = tmp.Upsert(urlEncode(v.Key), urlEncode(v.Value))
}
return tmp.SplitToString("=", "&")
}
func (p keyPairs) UrlEncodedString() string {
if len(p) == 0 {
return ""
}
tmp := url.Values{}
for _, el := range p {
tmp.Add(el.Key, el.Value)
}
return tmp.Encode()
}
func (p keyPairs) Keys() []string {
result := make([]string, p.Len())
for index, el := range p {
result[index] = el.Key
}
return result
}
func (p keyPairs) Len() int {
return len(p)
}
func (p keyPairs) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p keyPairs) Less(i, j int) bool {
return p[i].Key < p[j].Key
}