qcloud.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "fmt"
  9. "net/http"
  10. "net/url"
  11. "sort"
  12. "time"
  13. "go-common/app/service/main/spy/model"
  14. "go-common/library/log"
  15. )
  16. func (d *Dao) hmacsha1(key, text string) (h string) {
  17. mac := hmac.New(sha1.New, []byte(key))
  18. mac.Write([]byte(text))
  19. h = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  20. return
  21. }
  22. func (d *Dao) makeURL(method string, action string, region string, secretID string, secretKey string,
  23. args url.Values, charset string, URL string) (req string) {
  24. args.Set("Nonce", fmt.Sprintf("%d", d.r.Uint32()))
  25. args.Set("Action", action)
  26. args.Set("Region", region)
  27. args.Set("SecretId", secretID)
  28. args.Set("Timestamp", fmt.Sprintf("%d", time.Now().Unix()))
  29. args.Set("Signature", d.hmacsha1(secretKey, fmt.Sprintf("%s%s?%s", method, URL, d.makeQueryString(args))))
  30. req = args.Encode()
  31. return
  32. }
  33. func (d *Dao) makeQueryString(v url.Values) (str string) {
  34. if v == nil {
  35. return ""
  36. }
  37. var buf bytes.Buffer
  38. keys := make([]string, 0, len(v))
  39. for k := range v {
  40. keys = append(keys, k)
  41. }
  42. sort.Strings(keys)
  43. for _, k := range keys {
  44. vs := v[k]
  45. prefix := k + "="
  46. for _, v := range vs {
  47. if buf.Len() > 0 {
  48. buf.WriteString("&")
  49. }
  50. buf.WriteString(prefix)
  51. buf.WriteString(v)
  52. }
  53. }
  54. return buf.String()
  55. }
  56. // RegisterProtection register protection.
  57. func (d *Dao) RegisterProtection(c context.Context, args url.Values, ip string) (level int8, err error) {
  58. query := d.makeURL("GET", d.c.Qcloud.Path, d.c.Qcloud.Region, d.c.Qcloud.SecretID,
  59. d.c.Qcloud.SecretKey, args, d.c.Qcloud.Charset, d.c.Qcloud.BaseURL)
  60. req, err := http.NewRequest("GET", "https://"+d.c.Qcloud.BaseURL+"?"+query, nil)
  61. if err != nil {
  62. log.Error("d.RegisterProtection uri(%s) error(%v)", query, err)
  63. return
  64. }
  65. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  66. res := &model.QcloudRegProResp{}
  67. if err = d.httpClient.Do(c, req, res); err != nil {
  68. log.Error("d.client.Do error(%v) | uri(%s)) res(%v)", err, query, res)
  69. return
  70. }
  71. if res.Code != 0 {
  72. err = fmt.Errorf("GET RegisterProtection req faild query(%s) resp(%v)", d.c.Qcloud.BaseURL+"?"+query, res)
  73. log.Error(" RegisterProtection fail res(%v)", res)
  74. return
  75. }
  76. level = res.Level
  77. log.Info("GET RegisterProtection suc query(%s) resp(%v)", query, res)
  78. return
  79. }