1
0

tencent-alarm.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package channel
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "math/rand"
  9. "message-pusher/model"
  10. "net/http"
  11. "net/url"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. type TencentAlarmResponse struct {
  18. Code int `json:"code"`
  19. Message string `json:"message"`
  20. CodeDesc string `json:"codeDesc"`
  21. }
  22. func SendTencentAlarmMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
  23. secretId := channel_.AppId
  24. secretKey := channel_.Secret
  25. policyId := channel_.AccountId
  26. region := channel_.Other
  27. if message.Description == "" {
  28. message.Description = message.Content
  29. }
  30. params := map[string]string{
  31. "Action": "SendCustomAlarmMsg",
  32. "Region": region,
  33. "Timestamp": strconv.FormatInt(time.Now().Unix(), 10),
  34. "Nonce": strconv.Itoa(rand.Intn(65535)),
  35. "SecretId": secretId,
  36. "policyId": policyId,
  37. "msg": message.Description,
  38. }
  39. keys := make([]string, 0, len(params))
  40. for key := range params {
  41. keys = append(keys, key)
  42. }
  43. sort.Strings(keys)
  44. srcStr := "GETmonitor.api.qcloud.com/v2/index.php?"
  45. for _, key := range keys {
  46. srcStr += key + "=" + params[key] + "&"
  47. }
  48. srcStr = srcStr[:len(srcStr)-1]
  49. h := hmac.New(sha1.New, []byte(secretKey))
  50. h.Write([]byte(srcStr))
  51. signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
  52. params["Signature"] = signature
  53. urlStr := "https://monitor.api.qcloud.com/v2/index.php?" + urlEncode(params)
  54. client := &http.Client{}
  55. req, err := http.NewRequest("GET", urlStr, nil)
  56. if err != nil {
  57. return err
  58. }
  59. resp, err := client.Do(req)
  60. if err != nil {
  61. return err
  62. }
  63. var response TencentAlarmResponse
  64. err = json.NewDecoder(resp.Body).Decode(&response)
  65. if err != nil {
  66. return err
  67. }
  68. if response.Code != 0 {
  69. return errors.New(response.Message)
  70. }
  71. return nil
  72. }
  73. func urlEncode(params map[string]string) string {
  74. var encodedParams []string
  75. for key, value := range params {
  76. encodedParams = append(encodedParams, url.QueryEscape(key)+"="+url.QueryEscape(value))
  77. }
  78. return strings.Join(encodedParams, "&")
  79. }