背景
最近在用Go实现业务日志实时监控,当捕捉到error级别的日志时,想要推送钉钉消息到群里进行通知,下面代码实现了简单消息及markdown消息推送到钉钉机器人webhook的操作,供大家参考。
代码实现
代码语言:javascript复制package main
import (
"fmt"
// 先下载这个包,go get github.com/mikemintang/go-curl
"github.com/mikemintang/go-curl"
)
func main() {
// 钉钉机器人webhook
url := "https://oapi.dingtalk.com/robot/send?access_token=your_access_token"
// 添加头信息
headers := map[string]string{
"Content-Type": "application/json",
}
/*
发送简单文本消息
content := make(map[string]string)
content["content"] = "hello"
postData := map[string]interface{}{
"msgtype": "text",
"text": content ,
}
*/
// 发送markdown消息
content := make(map[string]string)
content["content"] = "hello"
postData := map[string]interface{}{
"msgtype": "markdown" ,
"markdown": map[string]string{
"title": "ERROR",
"text": "## Please check nown "
"> 1. firstn"
"> 2. secondn",
},
"at": map[string]interface{}{
"atMobiles":[]string{"18888888888","18866666666"},
"isAtAll": false,
},
}
// 链式操作
req := curl.NewRequest()
resp, err := req.
SetUrl(url).
SetHeaders(headers).
SetPostData(postData).
Post()
// 返回处理
if err != nil {
fmt.Println(err)
} else {
if resp.IsOk() {
fmt.Println(resp.Body)
} else {
fmt.Println(resp.Raw)
}
}
}