gitee.com/lh-her-team/common@v1.5.1/alert/sdk_alert.go (about) 1 package alert 2 3 import ( 4 "errors" 5 "fmt" 6 "net/http" 7 8 "gitee.com/lh-her-team/common/httputils" 9 "gitee.com/lh-her-team/common/json" 10 ) 11 12 const ( 13 USER_ALERT_LEVEL_INFO = "info" 14 USER_ALERT_LEVEL_WARN = "warning" 15 USER_ALERT_URI = "/cm-alert-api/v1/alert/user" 16 ) 17 18 type ErrCode uint32 19 20 const ( 21 ErrCodeOK ErrCode = 0 22 ) 23 24 type BaseResp struct { 25 RetCode uint32 `json:"retcode"` 26 RetMsg string `json:"retmsg"` 27 } 28 29 type UserAlertModel struct { 30 // (1)必填字段 31 // 告警级别,支持:USER_ALERT_LEVEL_INFO、USER_ALERT_LEVEL_WARN 32 // 仅部分告警触达方式下有效 33 Level string `json:"level"` 34 // 告警标题 35 Subject string `json:"subject"` 36 // 告警内容 37 Content string `json:"content"` 38 // (2)选填字段 39 // 告警邮件接收者邮箱,设置该字段后,将发送邮件 40 Receivers []string `json:"receivers"` 41 // 告警webhooks,当前仅支持企业微信群,设置该字段,将发送到指定企业微信群 42 Webhooks []string `json:"webhooks"` 43 // 附件名(邮件) 44 AttachName string `json:"attach_name"` 45 // 附件base64编码内容(邮件),大小限制在配置文件attach_file_size指定 46 AttachFile string `json:"attach_file"` 47 } 48 49 type AlertClient struct { 50 //自定义Client 51 customClient *http.Client 52 // 告警中心地址 53 alarmCenterUrl string 54 // 告警信息 55 alertInfo UserAlertModel 56 } 57 58 func (client AlertClient) SendUserAlertSync() error { 59 if err := client.checkParams(); err != nil { 60 return err 61 } 62 resp, err := httputils.POST(client.customClient, client.alarmCenterUrl+USER_ALERT_URI, client.alertInfo) 63 if err != nil { 64 return err 65 } 66 var alertResp BaseResp 67 err = json.Unmarshal(resp, &alertResp) 68 if err != nil { 69 return fmt.Errorf("unmarshal resp failed, %s", err) 70 } 71 if alertResp.RetCode != uint32(ErrCodeOK) { 72 return fmt.Errorf("recv err, errCode:%d, errMsg:%s", alertResp.RetCode, alertResp.RetMsg) 73 } 74 return nil 75 } 76 77 func (client AlertClient) SendUserAlert() error { 78 if err := client.checkParams(); err != nil { 79 return err 80 } 81 go func() { 82 _, _ = httputils.POST(client.customClient, client.alarmCenterUrl+USER_ALERT_URI, client.alertInfo) 83 }() 84 return nil 85 } 86 87 func (client AlertClient) checkParams() error { 88 if client.alarmCenterUrl == "" { 89 return errors.New("alert center url is empty") 90 } 91 if client.alertInfo.Subject == "" { 92 return errors.New("alert subject is empty") 93 } 94 if client.alertInfo.Content == "" { 95 return errors.New("alert content is empty") 96 } 97 if client.alertInfo.Level != "" { 98 if client.alertInfo.Level != USER_ALERT_LEVEL_INFO && client.alertInfo.Level != USER_ALERT_LEVEL_WARN { 99 return errors.New("alert level is invalid") 100 } 101 } else { 102 client.alertInfo.Level = USER_ALERT_LEVEL_WARN 103 } 104 if len(client.alertInfo.Receivers) == 0 && len(client.alertInfo.Webhooks) == 0 { 105 return errors.New("all receivers and webhooks are empty") 106 } 107 return nil 108 }