alarm_msg.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package alarm_msg
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "eta/eta_forum_hub/utils"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "strings"
  10. "time"
  11. )
  12. // SendAlarmMsg
  13. // projectName-项目名称
  14. // runMode-运行模式
  15. // msgBody-消息内容
  16. // level:消息基本,1:提示消息,2:警告消息,3:严重错误信息,默认为1 提示消息
  17. func SendAlarmMsg(msgBody string, level int) {
  18. if utils.AlarmMsgUrl == `` {
  19. return
  20. }
  21. params := make(map[string]interface{})
  22. params["ProjectName"] = utils.APP_NAME_CN
  23. params["RunMode"] = utils.RunMode
  24. params["MsgBody"] = msgBody
  25. params["Level"] = level
  26. param, err := json.Marshal(params)
  27. if err != nil {
  28. utils.FileLog.Info("SendAlarmMsg json.Marshal Err:" + err.Error())
  29. return
  30. }
  31. _, _ = Post(utils.AlarmMsgUrl, string(param), "application/json")
  32. }
  33. func HttpPost(url, postData string, params ...string) ([]byte, error) {
  34. contentType := "application/x-www-form-urlencoded;charset=utf-8"
  35. if len(params) > 0 && params[0] != "" {
  36. contentType = params[0]
  37. }
  38. sTime := time.Now()
  39. resp, err := http.Post(url,
  40. contentType,
  41. strings.NewReader(postData))
  42. eTime := time.Now()
  43. t := eTime.Sub(sTime).Nanoseconds() / 1000000
  44. if err != nil {
  45. return nil, err
  46. }
  47. defer resp.Body.Close()
  48. b, err := ioutil.ReadAll(resp.Body)
  49. fmt.Println(t, "ms", "POST", "URL", url, "DATA", postData, "RESPONSE", string(b))
  50. return b, err
  51. }
  52. func Post(url, postData string, params ...string) ([]byte, error) {
  53. if strings.HasPrefix(url, "https://") {
  54. return HttpsPost(url, postData, params...)
  55. } else {
  56. return HttpPost(url, postData, params...)
  57. }
  58. }
  59. func HttpsPost(url, postData string, params ...string) ([]byte, error) {
  60. body := ioutil.NopCloser(strings.NewReader(postData))
  61. tr := &http.Transport{
  62. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  63. DisableCompression: true,
  64. }
  65. client := &http.Client{Transport: tr}
  66. req, err := http.NewRequest("POST", url, body)
  67. if err != nil {
  68. return nil, err
  69. }
  70. contentType := "application/x-www-form-urlencoded;charset=utf-8"
  71. if len(params) > 0 && params[0] != "" {
  72. contentType = params[0]
  73. }
  74. req.Header.Set("Content-Type", contentType)
  75. sTime := time.Now()
  76. resp, err := client.Do(req)
  77. eTime := time.Now()
  78. t := eTime.Sub(sTime).Nanoseconds() / 1000000
  79. if err != nil {
  80. return nil, err
  81. }
  82. defer resp.Body.Close()
  83. b, err := ioutil.ReadAll(resp.Body)
  84. fmt.Println(t, "ms", "POST", "URL", url, "DATA", postData, "RESPONSE", string(b))
  85. return b, err
  86. }