開始配置
在grafana管理界面WechatIMG7.jpeg
Name: 自己隨便取
Type: 選擇webhook
封裝發(fā)消息類型
通過配置上圖中的Url(這里可以自己隨便寫個api,接收grafana傳過來的參數(shù)),所傳參數(shù)如下
{
"imageUrl": "https://domain.com/assets/img/blog/mixed_styles.png",
"message": "Someone is testing the alert notification within grafana.",
"ruleUrl": "http://domain.com/rules/",
"title": "[Alerting] Test notification"
}
上代碼(通過自己封裝的api, 去請求微信)
部分代碼
type Hook struct {
DashboardId string `json:"dashboardId"`
EvalMatches string `json:"evalMatches"`
ImageUrl string `json:"imageUrl"`
Message string `json:"message"`
OrgId string `json:"orgId"`
PanelId string `json:"panelId"`
RuleId string `json:"ruleId"`
RuleName string `json:"ruleName"`
RuleUrl string `json:"ruleUrl"`
State string `json:"state"`
Tags string `json:"tags"`
Title string `json:"title"`
}
const (
Url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="
OKMsg = "告警恢復(fù)"
AlertingMsg = "觸發(fā)告警"
OK = "OK"
Alerting = "Alerting"
ColorGreen = "info"
ColorGray = "comment"
ColorRed = "warning"
)
// 發(fā)送消息
func SendMsg(c *gin.Context) {
h := &Hook{}
if err := c.BindJSON(&h); err != nil {
fmt.Println(err)
_, _ = c.Writer.WriteString("Error on JSON format")
return
}
marshal, _ := json.Marshal(h)
fmt.Println("接受參數(shù)數(shù)據(jù):", string(marshal))
// 字符串替換
h.RuleUrl = strings.ReplaceAll(h.RuleUrl, ":3000", "")
color := ColorGreen
if strings.Contains(h.Title, OK) {
h.Title = strings.ReplaceAll(h.Title, OK, OKMsg)
} else {
h.Title = strings.ReplaceAll(h.Title, Alerting, AlertingMsg)
color = ColorRed
}
// Send to WeChat Work
url := Url + c.Query("key")
// 處理數(shù)據(jù)格式
msgStr := MsgMarkdown(h, color)
if c.Query("type") == "news" {
msgStr = MsgNews(h)
}
fmt.Println("發(fā)送的消息是:", msgStr)
jsonStr := []byte(msgStr)
// 發(fā)送http請求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
_, _ = c.Writer.WriteString("Error sending to WeChat Work API")
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("shuju:", string(body))
_, _ = c.Writer.Write(body)
return
}
// 發(fā)送消息類型 news
func MsgNews(h *Hook) string {
return fmt.Sprintf(`
{
"msgtype": "news",
"news": {
"articles": [
{
"title": "%s",
"description": "%s",
"url": "%s",
"picurl": "%s"
}
]
}
}
`, h.Title, h.Message, h.RuleUrl, h.ImageUrl)
}
// 發(fā)送消息類型
func MsgMarkdown(h *Hook, color string) string {
return fmt.Sprintf(`
{
"msgtype": "markdown",
"markdown": {
"content": "<font color=\"%s\">%s</font>\r\n<font color=\"comment\">%s\r\n[點擊查看詳情](%s)</font>"
}
}`, color, h.Title, h.Message, h.RuleUrl, h.ImageUrl)
}
完整代碼 github
企業(yè)微信配置這里不再講解
- 前提你已經(jīng)在 企業(yè)微信文檔 申請過賬號耙考,也已經(jīng)配置好配置好key
打包文件
go build -o wechat-alert main.go
配置請求方式
1. 在grafana中配置webhook
2. Webhook settings里添寫
http://你的ip:88/send?key=微信的key
3. 點擊Send Test
備注:Username和Password 無關(guān)緊要,可以隨意填寫酌摇。
備注
代碼里實現(xiàn)了 發(fā)送企業(yè)微信的兩種類型的消息轧简。
- markdown(默認)
- news