service.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. // This file is auto-generated, don't edit it. Thanks.
  2. /**
  3. * This is for OpenApi Util
  4. */
  5. package service
  6. import (
  7. "bytes"
  8. "crypto"
  9. "crypto/hmac"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/sha1"
  13. "crypto/sha256"
  14. "crypto/x509"
  15. "encoding/base64"
  16. "encoding/hex"
  17. "encoding/json"
  18. "encoding/pem"
  19. "errors"
  20. "fmt"
  21. "hash"
  22. "io"
  23. "net/http"
  24. "net/textproto"
  25. "net/url"
  26. "reflect"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "time"
  31. util "github.com/alibabacloud-go/tea-utils/v2/service"
  32. "github.com/alibabacloud-go/tea/tea"
  33. "github.com/tjfoc/gmsm/sm3"
  34. )
  35. const (
  36. PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
  37. PEM_END = "\n-----END RSA PRIVATE KEY-----"
  38. )
  39. type Sorter struct {
  40. Keys []string
  41. Vals []string
  42. }
  43. func newSorter(m map[string]string) *Sorter {
  44. hs := &Sorter{
  45. Keys: make([]string, 0, len(m)),
  46. Vals: make([]string, 0, len(m)),
  47. }
  48. for k, v := range m {
  49. hs.Keys = append(hs.Keys, k)
  50. hs.Vals = append(hs.Vals, v)
  51. }
  52. return hs
  53. }
  54. // Sort is an additional function for function SignHeader.
  55. func (hs *Sorter) Sort() {
  56. sort.Sort(hs)
  57. }
  58. // Len is an additional function for function SignHeader.
  59. func (hs *Sorter) Len() int {
  60. return len(hs.Vals)
  61. }
  62. // Less is an additional function for function SignHeader.
  63. func (hs *Sorter) Less(i, j int) bool {
  64. return bytes.Compare([]byte(hs.Keys[i]), []byte(hs.Keys[j])) < 0
  65. }
  66. // Swap is an additional function for function SignHeader.
  67. func (hs *Sorter) Swap(i, j int) {
  68. hs.Vals[i], hs.Vals[j] = hs.Vals[j], hs.Vals[i]
  69. hs.Keys[i], hs.Keys[j] = hs.Keys[j], hs.Keys[i]
  70. }
  71. /**
  72. * Convert all params of body other than type of readable into content
  73. * @param body source Model
  74. * @param content target Model
  75. * @return void
  76. */
  77. func Convert(body interface{}, content interface{}) {
  78. res := make(map[string]interface{})
  79. val := reflect.ValueOf(body).Elem()
  80. dataType := val.Type()
  81. for i := 0; i < dataType.NumField(); i++ {
  82. field := dataType.Field(i)
  83. name, _ := field.Tag.Lookup("json")
  84. name = strings.Split(name, ",omitempty")[0]
  85. _, ok := val.Field(i).Interface().(io.Reader)
  86. if !ok {
  87. res[name] = val.Field(i).Interface()
  88. }
  89. }
  90. byt, _ := json.Marshal(res)
  91. json.Unmarshal(byt, content)
  92. }
  93. /**
  94. * Get the string to be signed according to request
  95. * @param request which contains signed messages
  96. * @return the signed string
  97. */
  98. func GetStringToSign(request *tea.Request) (_result *string) {
  99. return tea.String(getStringToSign(request))
  100. }
  101. func getStringToSign(request *tea.Request) string {
  102. resource := tea.StringValue(request.Pathname)
  103. queryParams := request.Query
  104. // sort QueryParams by key
  105. var queryKeys []string
  106. for key := range queryParams {
  107. queryKeys = append(queryKeys, key)
  108. }
  109. sort.Strings(queryKeys)
  110. tmp := ""
  111. for i := 0; i < len(queryKeys); i++ {
  112. queryKey := queryKeys[i]
  113. v := tea.StringValue(queryParams[queryKey])
  114. if v != "" {
  115. tmp = tmp + "&" + queryKey + "=" + v
  116. } else {
  117. tmp = tmp + "&" + queryKey
  118. }
  119. }
  120. if tmp != "" {
  121. tmp = strings.TrimLeft(tmp, "&")
  122. resource = resource + "?" + tmp
  123. }
  124. return getSignedStr(request, resource)
  125. }
  126. func getSignedStr(req *tea.Request, canonicalizedResource string) string {
  127. temp := make(map[string]string)
  128. for k, v := range req.Headers {
  129. if strings.HasPrefix(strings.ToLower(k), "x-acs-") {
  130. temp[strings.ToLower(k)] = tea.StringValue(v)
  131. }
  132. }
  133. hs := newSorter(temp)
  134. // Sort the temp by the ascending order
  135. hs.Sort()
  136. // Get the canonicalizedOSSHeaders
  137. canonicalizedOSSHeaders := ""
  138. for i := range hs.Keys {
  139. canonicalizedOSSHeaders += hs.Keys[i] + ":" + hs.Vals[i] + "\n"
  140. }
  141. // Give other parameters values
  142. // when sign URL, date is expires
  143. date := tea.StringValue(req.Headers["date"])
  144. accept := tea.StringValue(req.Headers["accept"])
  145. contentType := tea.StringValue(req.Headers["content-type"])
  146. contentMd5 := tea.StringValue(req.Headers["content-md5"])
  147. signStr := tea.StringValue(req.Method) + "\n" + accept + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource
  148. return signStr
  149. }
  150. /**
  151. * Get signature according to stringToSign, secret
  152. * @param stringToSign the signed string
  153. * @param secret accesskey secret
  154. * @return the signature
  155. */
  156. func GetROASignature(stringToSign *string, secret *string) (_result *string) {
  157. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(tea.StringValue(secret)))
  158. io.WriteString(h, tea.StringValue(stringToSign))
  159. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  160. return tea.String(signedStr)
  161. }
  162. func GetEndpoint(endpoint *string, server *bool, endpointType *string) *string {
  163. if tea.StringValue(endpointType) == "internal" {
  164. strs := strings.Split(tea.StringValue(endpoint), ".")
  165. strs[0] += "-internal"
  166. endpoint = tea.String(strings.Join(strs, "."))
  167. }
  168. if tea.BoolValue(server) && tea.StringValue(endpointType) == "accelerate" {
  169. return tea.String("oss-accelerate.aliyuncs.com")
  170. }
  171. return endpoint
  172. }
  173. func HexEncode(raw []byte) *string {
  174. return tea.String(hex.EncodeToString(raw))
  175. }
  176. func Hash(raw []byte, signatureAlgorithm *string) []byte {
  177. signType := tea.StringValue(signatureAlgorithm)
  178. if signType == "ACS3-HMAC-SHA256" || signType == "ACS3-RSA-SHA256" {
  179. h := sha256.New()
  180. h.Write(raw)
  181. return h.Sum(nil)
  182. } else if signType == "ACS3-HMAC-SM3" {
  183. h := sm3.New()
  184. h.Write(raw)
  185. return h.Sum(nil)
  186. }
  187. return nil
  188. }
  189. func GetEncodePath(path *string) *string {
  190. uri := tea.StringValue(path)
  191. strs := strings.Split(uri, "/")
  192. for i, v := range strs {
  193. strs[i] = url.QueryEscape(v)
  194. }
  195. uri = strings.Join(strs, "/")
  196. uri = strings.Replace(uri, "+", "%20", -1)
  197. uri = strings.Replace(uri, "*", "%2A", -1)
  198. uri = strings.Replace(uri, "%7E", "~", -1)
  199. return tea.String(uri)
  200. }
  201. func GetEncodeParam(param *string) *string {
  202. uri := tea.StringValue(param)
  203. uri = url.QueryEscape(uri)
  204. uri = strings.Replace(uri, "+", "%20", -1)
  205. uri = strings.Replace(uri, "*", "%2A", -1)
  206. uri = strings.Replace(uri, "%7E", "~", -1)
  207. return tea.String(uri)
  208. }
  209. func GetAuthorization(request *tea.Request, signatureAlgorithm, payload, acesskey, secret *string) *string {
  210. canonicalURI := tea.StringValue(request.Pathname)
  211. if canonicalURI == "" {
  212. canonicalURI = "/"
  213. }
  214. canonicalURI = strings.Replace(canonicalURI, "+", "%20", -1)
  215. canonicalURI = strings.Replace(canonicalURI, "*", "%2A", -1)
  216. canonicalURI = strings.Replace(canonicalURI, "%7E", "~", -1)
  217. method := tea.StringValue(request.Method)
  218. canonicalQueryString := getCanonicalQueryString(request.Query)
  219. canonicalheaders, signedHeaders := getCanonicalHeaders(request.Headers)
  220. canonicalRequest := method + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalheaders + "\n" +
  221. strings.Join(signedHeaders, ";") + "\n" + tea.StringValue(payload)
  222. signType := tea.StringValue(signatureAlgorithm)
  223. StringToSign := signType + "\n" + tea.StringValue(HexEncode(Hash([]byte(canonicalRequest), signatureAlgorithm)))
  224. signature := tea.StringValue(HexEncode(SignatureMethod(tea.StringValue(secret), StringToSign, signType)))
  225. auth := signType + " Credential=" + tea.StringValue(acesskey) + ",SignedHeaders=" +
  226. strings.Join(signedHeaders, ";") + ",Signature=" + signature
  227. return tea.String(auth)
  228. }
  229. func SignatureMethod(secret, source, signatureAlgorithm string) []byte {
  230. if signatureAlgorithm == "ACS3-HMAC-SHA256" {
  231. h := hmac.New(sha256.New, []byte(secret))
  232. h.Write([]byte(source))
  233. return h.Sum(nil)
  234. } else if signatureAlgorithm == "ACS3-HMAC-SM3" {
  235. h := hmac.New(sm3.New, []byte(secret))
  236. h.Write([]byte(source))
  237. return h.Sum(nil)
  238. } else if signatureAlgorithm == "ACS3-RSA-SHA256" {
  239. return rsaSign(source, secret)
  240. }
  241. return nil
  242. }
  243. func rsaSign(content, secret string) []byte {
  244. h := crypto.SHA256.New()
  245. h.Write([]byte(content))
  246. hashed := h.Sum(nil)
  247. priv, err := parsePrivateKey(secret)
  248. if err != nil {
  249. return nil
  250. }
  251. sign, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hashed)
  252. if err != nil {
  253. return nil
  254. }
  255. return sign
  256. }
  257. func parsePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
  258. privateKey = formatPrivateKey(privateKey)
  259. block, _ := pem.Decode([]byte(privateKey))
  260. if block == nil {
  261. return nil, errors.New("PrivateKey is invalid")
  262. }
  263. priKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  264. if err != nil {
  265. return nil, err
  266. }
  267. switch priKey.(type) {
  268. case *rsa.PrivateKey:
  269. return priKey.(*rsa.PrivateKey), nil
  270. default:
  271. return nil, nil
  272. }
  273. }
  274. func formatPrivateKey(privateKey string) string {
  275. if !strings.HasPrefix(privateKey, PEM_BEGIN) {
  276. privateKey = PEM_BEGIN + privateKey
  277. }
  278. if !strings.HasSuffix(privateKey, PEM_END) {
  279. privateKey += PEM_END
  280. }
  281. return privateKey
  282. }
  283. func getCanonicalHeaders(headers map[string]*string) (string, []string) {
  284. tmp := make(map[string]string)
  285. tmpHeader := http.Header{}
  286. for k, v := range headers {
  287. if strings.HasPrefix(strings.ToLower(k), "x-acs-") || strings.ToLower(k) == "host" ||
  288. strings.ToLower(k) == "content-type" {
  289. tmp[strings.ToLower(k)] = strings.TrimSpace(tea.StringValue(v))
  290. tmpHeader.Add(strings.ToLower(k), strings.TrimSpace(tea.StringValue(v)))
  291. }
  292. }
  293. hs := newSorter(tmp)
  294. // Sort the temp by the ascending order
  295. hs.Sort()
  296. canonicalheaders := ""
  297. for _, key := range hs.Keys {
  298. vals := tmpHeader[textproto.CanonicalMIMEHeaderKey(key)]
  299. sort.Strings(vals)
  300. canonicalheaders += key + ":" + strings.Join(vals, ",") + "\n"
  301. }
  302. return canonicalheaders, hs.Keys
  303. }
  304. func getCanonicalQueryString(query map[string]*string) string {
  305. canonicalQueryString := ""
  306. if tea.BoolValue(util.IsUnset(query)) {
  307. return canonicalQueryString
  308. }
  309. tmp := make(map[string]string)
  310. for k, v := range query {
  311. tmp[k] = tea.StringValue(v)
  312. }
  313. hs := newSorter(tmp)
  314. // Sort the temp by the ascending order
  315. hs.Sort()
  316. for i := range hs.Keys {
  317. if hs.Vals[i] != "" {
  318. canonicalQueryString += "&" + hs.Keys[i] + "=" + url.QueryEscape(hs.Vals[i])
  319. } else {
  320. canonicalQueryString += "&" + hs.Keys[i] + "="
  321. }
  322. }
  323. canonicalQueryString = strings.Replace(canonicalQueryString, "+", "%20", -1)
  324. canonicalQueryString = strings.Replace(canonicalQueryString, "*", "%2A", -1)
  325. canonicalQueryString = strings.Replace(canonicalQueryString, "%7E", "~", -1)
  326. if canonicalQueryString != "" {
  327. canonicalQueryString = strings.TrimLeft(canonicalQueryString, "&")
  328. }
  329. return canonicalQueryString
  330. }
  331. /**
  332. * Parse filter into a form string
  333. * @param filter object
  334. * @return the string
  335. */
  336. func ToForm(filter map[string]interface{}) (_result *string) {
  337. tmp := make(map[string]interface{})
  338. byt, _ := json.Marshal(filter)
  339. d := json.NewDecoder(bytes.NewReader(byt))
  340. d.UseNumber()
  341. _ = d.Decode(&tmp)
  342. result := make(map[string]*string)
  343. for key, value := range tmp {
  344. filterValue := reflect.ValueOf(value)
  345. flatRepeatedList(filterValue, result, key)
  346. }
  347. m := util.AnyifyMapValue(result)
  348. return util.ToFormString(m)
  349. }
  350. func flatRepeatedList(dataValue reflect.Value, result map[string]*string, prefix string) {
  351. if !dataValue.IsValid() {
  352. return
  353. }
  354. dataType := dataValue.Type()
  355. if dataType.Kind().String() == "slice" {
  356. handleRepeatedParams(dataValue, result, prefix)
  357. } else if dataType.Kind().String() == "map" {
  358. handleMap(dataValue, result, prefix)
  359. } else {
  360. result[prefix] = tea.String(fmt.Sprintf("%v", dataValue.Interface()))
  361. }
  362. }
  363. func handleRepeatedParams(repeatedFieldValue reflect.Value, result map[string]*string, prefix string) {
  364. if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
  365. for m := 0; m < repeatedFieldValue.Len(); m++ {
  366. elementValue := repeatedFieldValue.Index(m)
  367. key := prefix + "." + strconv.Itoa(m+1)
  368. fieldValue := reflect.ValueOf(elementValue.Interface())
  369. if fieldValue.Kind().String() == "map" {
  370. handleMap(fieldValue, result, key)
  371. } else {
  372. result[key] = tea.String(fmt.Sprintf("%v", fieldValue.Interface()))
  373. }
  374. }
  375. }
  376. }
  377. func handleMap(valueField reflect.Value, result map[string]*string, prefix string) {
  378. if valueField.IsValid() && valueField.String() != "" {
  379. valueFieldType := valueField.Type()
  380. if valueFieldType.Kind().String() == "map" {
  381. var byt []byte
  382. byt, _ = json.Marshal(valueField.Interface())
  383. cache := make(map[string]interface{})
  384. d := json.NewDecoder(bytes.NewReader(byt))
  385. d.UseNumber()
  386. _ = d.Decode(&cache)
  387. for key, value := range cache {
  388. pre := ""
  389. if prefix != "" {
  390. pre = prefix + "." + key
  391. } else {
  392. pre = key
  393. }
  394. fieldValue := reflect.ValueOf(value)
  395. flatRepeatedList(fieldValue, result, pre)
  396. }
  397. }
  398. }
  399. }
  400. /**
  401. * Get timestamp
  402. * @return the timestamp string
  403. */
  404. func GetTimestamp() (_result *string) {
  405. gmt := time.FixedZone("GMT", 0)
  406. return tea.String(time.Now().In(gmt).Format("2006-01-02T15:04:05Z"))
  407. }
  408. /**
  409. * Parse filter into a object which's type is map[string]string
  410. * @param filter query param
  411. * @return the object
  412. */
  413. func Query(filter interface{}) (_result map[string]*string) {
  414. tmp := make(map[string]interface{})
  415. byt, _ := json.Marshal(filter)
  416. d := json.NewDecoder(bytes.NewReader(byt))
  417. d.UseNumber()
  418. _ = d.Decode(&tmp)
  419. result := make(map[string]*string)
  420. for key, value := range tmp {
  421. filterValue := reflect.ValueOf(value)
  422. flatRepeatedList(filterValue, result, key)
  423. }
  424. return result
  425. }
  426. /**
  427. * Get signature according to signedParams, method and secret
  428. * @param signedParams params which need to be signed
  429. * @param method http method e.g. GET
  430. * @param secret AccessKeySecret
  431. * @return the signature
  432. */
  433. func GetRPCSignature(signedParams map[string]*string, method *string, secret *string) (_result *string) {
  434. stringToSign := buildRpcStringToSign(signedParams, tea.StringValue(method))
  435. signature := sign(stringToSign, tea.StringValue(secret), "&")
  436. return tea.String(signature)
  437. }
  438. /**
  439. * Parse array into a string with specified style
  440. * @param array the array
  441. * @param prefix the prefix string
  442. * @style specified style e.g. repeatList
  443. * @return the string
  444. */
  445. func ArrayToStringWithSpecifiedStyle(array interface{}, prefix *string, style *string) (_result *string) {
  446. if tea.BoolValue(util.IsUnset(array)) {
  447. return tea.String("")
  448. }
  449. sty := tea.StringValue(style)
  450. if sty == "repeatList" {
  451. tmp := map[string]interface{}{
  452. tea.StringValue(prefix): array,
  453. }
  454. return flatRepeatList(tmp)
  455. } else if sty == "simple" || sty == "spaceDelimited" || sty == "pipeDelimited" {
  456. return flatArray(array, sty)
  457. } else if sty == "json" {
  458. return util.ToJSONString(array)
  459. }
  460. return tea.String("")
  461. }
  462. func ParseToMap(in interface{}) map[string]interface{} {
  463. if tea.BoolValue(util.IsUnset(in)) {
  464. return nil
  465. }
  466. tmp := make(map[string]interface{})
  467. byt, _ := json.Marshal(in)
  468. d := json.NewDecoder(bytes.NewReader(byt))
  469. d.UseNumber()
  470. err := d.Decode(&tmp)
  471. if err != nil {
  472. return nil
  473. }
  474. return tmp
  475. }
  476. func flatRepeatList(filter map[string]interface{}) (_result *string) {
  477. tmp := make(map[string]interface{})
  478. byt, _ := json.Marshal(filter)
  479. d := json.NewDecoder(bytes.NewReader(byt))
  480. d.UseNumber()
  481. _ = d.Decode(&tmp)
  482. result := make(map[string]*string)
  483. for key, value := range tmp {
  484. filterValue := reflect.ValueOf(value)
  485. flatRepeatedList(filterValue, result, key)
  486. }
  487. res := make(map[string]string)
  488. for k, v := range result {
  489. res[k] = tea.StringValue(v)
  490. }
  491. hs := newSorter(res)
  492. hs.Sort()
  493. // Get the canonicalizedOSSHeaders
  494. t := ""
  495. for i := range hs.Keys {
  496. if i == len(hs.Keys)-1 {
  497. t += hs.Keys[i] + "=" + hs.Vals[i]
  498. } else {
  499. t += hs.Keys[i] + "=" + hs.Vals[i] + "&&"
  500. }
  501. }
  502. return tea.String(t)
  503. }
  504. func flatArray(array interface{}, sty string) *string {
  505. t := reflect.ValueOf(array)
  506. strs := make([]string, 0)
  507. for i := 0; i < t.Len(); i++ {
  508. tmp := t.Index(i)
  509. if tmp.Kind() == reflect.Ptr || tmp.Kind() == reflect.Interface {
  510. tmp = tmp.Elem()
  511. }
  512. if tmp.Kind() == reflect.Ptr {
  513. tmp = tmp.Elem()
  514. }
  515. if tmp.Kind() == reflect.String {
  516. strs = append(strs, tmp.String())
  517. } else {
  518. inter := tmp.Interface()
  519. byt, _ := json.Marshal(inter)
  520. strs = append(strs, string(byt))
  521. }
  522. }
  523. str := ""
  524. if sty == "simple" {
  525. str = strings.Join(strs, ",")
  526. } else if sty == "spaceDelimited" {
  527. str = strings.Join(strs, " ")
  528. } else if sty == "pipeDelimited" {
  529. str = strings.Join(strs, "|")
  530. }
  531. return tea.String(str)
  532. }
  533. func buildRpcStringToSign(signedParam map[string]*string, method string) (stringToSign string) {
  534. signParams := make(map[string]string)
  535. for key, value := range signedParam {
  536. signParams[key] = tea.StringValue(value)
  537. }
  538. stringToSign = getUrlFormedMap(signParams)
  539. stringToSign = strings.Replace(stringToSign, "+", "%20", -1)
  540. stringToSign = strings.Replace(stringToSign, "*", "%2A", -1)
  541. stringToSign = strings.Replace(stringToSign, "%7E", "~", -1)
  542. stringToSign = url.QueryEscape(stringToSign)
  543. stringToSign = method + "&%2F&" + stringToSign
  544. return
  545. }
  546. func getUrlFormedMap(source map[string]string) (urlEncoded string) {
  547. urlEncoder := url.Values{}
  548. for key, value := range source {
  549. urlEncoder.Add(key, value)
  550. }
  551. urlEncoded = urlEncoder.Encode()
  552. return
  553. }
  554. func sign(stringToSign, accessKeySecret, secretSuffix string) string {
  555. secret := accessKeySecret + secretSuffix
  556. signedBytes := shaHmac1(stringToSign, secret)
  557. signedString := base64.StdEncoding.EncodeToString(signedBytes)
  558. return signedString
  559. }
  560. func shaHmac1(source, secret string) []byte {
  561. key := []byte(secret)
  562. hmac := hmac.New(sha1.New, key)
  563. hmac.Write([]byte(source))
  564. return hmac.Sum(nil)
  565. }
  566. func getTimeLeft(rateLimit *string) (_result *int64) {
  567. if rateLimit != nil {
  568. pairs := strings.Split(tea.StringValue(rateLimit), ",")
  569. for _, pair := range pairs {
  570. kv := strings.Split(pair, ":")
  571. if len(kv) == 2 {
  572. key, value := kv[0], kv[1]
  573. if key == "TimeLeft" {
  574. timeLeftValue, err := strconv.ParseInt(value, 10, 64)
  575. if err != nil {
  576. return nil
  577. }
  578. return tea.Int64(timeLeftValue)
  579. }
  580. }
  581. }
  582. }
  583. return nil
  584. }
  585. /**
  586. * Get throttling param
  587. * @param the response headers
  588. * @return time left
  589. */
  590. func GetThrottlingTimeLeft(headers map[string]*string) (_result *int64) {
  591. rateLimitForUserApi := headers["x-ratelimit-user-api"]
  592. rateLimitForUser := headers["x-ratelimit-user"]
  593. timeLeftForUserApi := getTimeLeft(rateLimitForUserApi)
  594. timeLeftForUser := getTimeLeft(rateLimitForUser)
  595. if tea.Int64Value(timeLeftForUserApi) > tea.Int64Value(timeLeftForUser) {
  596. return timeLeftForUserApi
  597. } else {
  598. return timeLeftForUser
  599. }
  600. }