dingtalk.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package warning
  4. import (
  5. "bytes"
  6. "crypto/tls"
  7. "encoding/json"
  8. "gd_crontab/common.in/config"
  9. "gd_crontab/errors"
  10. "github.com/tidwall/gjson"
  11. "io/ioutil"
  12. "net/http"
  13. "strings"
  14. "time"
  15. )
  16. type HttpRequestWithHeadCommon struct {
  17. Url string
  18. Method string
  19. Head map[string]string
  20. TimeOut time.Duration
  21. Query map[string]string
  22. Body []byte
  23. }
  24. func joinGetRequestArgsCommon(data map[string]string) string {
  25. var path string
  26. if data != nil {
  27. path += "?"
  28. for k, v := range data {
  29. path += k + "=" + v + "&"
  30. }
  31. path = strings.TrimRight(path, "&")
  32. return path
  33. }
  34. return path
  35. }
  36. func (h HttpRequestWithHeadCommon) Request() ([]byte, error) {
  37. if len(h.Query) > 0 {
  38. h.Url = h.Url + joinGetRequestArgsCommon(h.Query)
  39. }
  40. request, err := http.NewRequest(h.Method, h.Url, bytes.NewReader(h.Body))
  41. for k, v := range h.Head {
  42. request.Header.Add(k, v)
  43. }
  44. //跳过证书验证
  45. tr := &http.Transport{
  46. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  47. }
  48. client := http.Client{
  49. Transport: tr,
  50. Timeout: h.TimeOut,
  51. }
  52. resp, err := client.Do(request)
  53. if err != nil {
  54. return nil, errors.VendorError
  55. }
  56. defer resp.Body.Close()
  57. if resp.StatusCode != http.StatusOK {
  58. return nil, errors.VendorError
  59. }
  60. contents, err := ioutil.ReadAll(resp.Body)
  61. if err != nil {
  62. return nil, errors.VendorError
  63. }
  64. return contents, nil
  65. }
  66. func RobotMsg(content string) (err error) {
  67. body := map[string]interface{}{
  68. "msgtype": "text",
  69. "text": map[string]interface{}{"content": content},
  70. }
  71. bytes, _ := json.Marshal(body)
  72. h := HttpRequestWithHeadCommon{
  73. Method: "POST",
  74. Url: config.Conf.ThirdPart.WarnWebhook,
  75. Body: bytes,
  76. TimeOut: 10 * time.Second,
  77. }
  78. bytes, err = h.Request()
  79. if err != nil {
  80. return errors.VendorError
  81. }
  82. errcode := gjson.GetBytes(bytes, "errcode").Int()
  83. //errmsg := gjson.GetBytes(bytes, "errmsg").String()
  84. if errcode != 0 {
  85. return errors.VendorError
  86. }
  87. return nil
  88. }