代码拉取完成,页面将自动刷新
package dingtalkutils
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"gitee.com/cfh008/runutils"
)
type DingtalkRobot struct {
Webhook string
Secret string
}
func hmacSha256(strToSign string, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(strToSign))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func (robot *DingtalkRobot) GetWebhookWithSignature() (result string) {
timestamp := time.Now().UnixNano() / 1e6
strToSign := fmt.Sprintf("%d\n%s", timestamp, robot.Secret)
sign := hmacSha256(strToSign, robot.Secret)
result = fmt.Sprintf("%s×tamp=%d&sign=%s", robot.Webhook, timestamp, sign)
return
}
func (robot *DingtalkRobot) SendMapData(data map[string]interface{}) (err error) {
url := robot.GetWebhookWithSignature()
b, doErr := json.Marshal(data)
if doErr != nil {
errInfo := fmt.Sprintf("%v call json.Marshal(%v) failed with %v", runutils.RunFuncName(), data, doErr)
err = fmt.Errorf(errInfo)
return
}
resp, doErr := http.Post(url,
"application/json",
bytes.NewBuffer(b))
if doErr != nil {
errInfo := fmt.Sprintf("%v call http.Post failed with %v", runutils.RunFuncName(), doErr)
err = fmt.Errorf(errInfo)
return
}
defer resp.Body.Close()
body, doErr := ioutil.ReadAll(resp.Body)
if doErr != nil {
errInfo := fmt.Sprintf("%v call ioutil.ReadAll failed with %v", runutils.RunFuncName(), doErr)
err = fmt.Errorf(errInfo)
return
}
var result map[string]interface{}
json.Unmarshal(body, &result)
// fmt.Println(string(body))
errcode := result["errcode"].(float64)
if errcode != 0 {
errInfo := fmt.Sprintf("%v result(%v) is abnormal", runutils.RunFuncName(), string(body))
err = fmt.Errorf(errInfo)
return
}
return
}
func SendMapData(webhook string, secret string, data map[string]interface{}) (err error) {
robot := DingtalkRobot{Webhook: webhook, Secret: secret}
return robot.SendMapData(data)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。