Go发送钉钉消息


type KV map[string]string
type DingtalkNoticeAt struct {
	AtMobiles []string `json:"atMobiles"`
	IsAtAll   bool     `json:"isAtAll"`
}

type DingtalkNotice struct {
	Msgtype  string           `json:"msgtype"`
	Markdown KV               `json:"markdown"`
	At       DingtalkNoticeAt `json:"at"`
}


func hmacSha256(stringToSign string, secret string) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(stringToSign))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

// Sign 发送钉钉消息
func Sign() string {
	secret := vars.Conf.Secret
	webhook := vars.Conf.Webhook
	timestamp := time.Now().UnixNano() / 1e6
	stringToSign := fmt.Sprintf("%d\n%s", timestamp, secret)
	sign := hmacSha256(stringToSign, secret)
	url := fmt.Sprintf("%s&timestamp=%d&sign=%s", webhook, timestamp, sign)
	return url
}

func Notice(){
	text := generate()  // 换行使用两个换行符 --> "\n\n"
	url := Sign()
	content, err := json.Marshal(text)
	if err != nil {
		panic(err)
	}

	request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(string(content)))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Content-Type", "Application/json")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer func() { response.Body.Close() }()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", body)
}
上一篇:攻防世界Web进阶篇——NewsCenter


下一篇:k8s学习记录,配置管理Secret(十八)