package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strings" "time" ) type SimpleRequest struct { Text SimpleRequestContent `json:"text"` Msgtype string `json:"msgtype"` } type SimpleRequestContent struct { Content string `json:"content"` } var UrlAddress = "https://oapi.dingtalk.com/robot/send?access_token=f092c30d******************" var Secret = "SEC2d31d9a834f********************" func main() { // 設置請求頭 requestBody := SimpleRequest{ Text: SimpleRequestContent{ Content: "simple request", }, Msgtype: "text", } reqBodyBox, _ := json.Marshal(requestBody) body := string(reqBodyBox) // 構建 簽名 // 把timestamp+"\n"+密鑰當做簽名字符串,使用HmacSHA256算法計算簽名,然后進行Base64 encode,最后再把簽名參數再進行urlEncode,得到最終的簽名(需要使用UTF-8字符集)。 timeStampNow := time.Now().UnixNano() / 1000000 signStr :=fmt.Sprintf("%d\n%s", timeStampNow, Secret) hash := hmac.New(sha256.New, []byte(Secret)) hash.Write([]byte(signStr)) sum := hash.Sum(nil) encode := base64.StdEncoding.EncodeToString(sum) urlEncode := url.QueryEscape(encode) // 構建 請求 url UrlAddress = fmt.Sprintf("%s×tamp=%d&sign=%s", UrlAddress, timeStampNow, urlEncode) // 構建 請求體 request, _ := http.NewRequest("POST", UrlAddress, strings.NewReader(body)) // 設置庫端口 client := &http.Client{} // 請求頭添加內容 request.Header.Set("Content-Type", "application/json") // 發送請求 response, _ := client.Do(request) fmt.Println("response: ", response) // 關閉 讀取 reader defer response.Body.Close() // 讀取內容 all, _ := ioutil.ReadAll(response.Body) fmt.Println("all: ", string(all)) }