package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" "time" ) type TemplateMsg struct { ToUser string `json:"touser"` TemplateId string `json:"template_id"` Url string `json:"url"` MiniProgram TemplateMsgMiniprogramInfo `json:"miniprogram"` Data map[string]TemplateMsgDataItem `json:"data"` } type TemplateMsgMiniprogramInfo struct { AppId string `json:"appid"` PagePath string `json:"pagepath"` } type TemplateMsgDataItem struct { Value string `json:"value"` Color string `json:"color"` } func sendTemplateMsg(bytesData []byte) string { reader := bytes.NewReader(bytesData) url := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=13_NI_fTDDbC34LHbs1qtNPxbCdL1dnzzL9vLadYLcc_fPufMWtaNpKadstYk_PvNrD8aeBHrJeeMjvEv_oI29WjTFyPlja2VEpma1paIpAoDm9TTwtNm45zsRdFhVP_QfbJUU0xypR1zM1Dd9XUSHjABAGET" resp, err := http.Post(url, "application/json;charset=utf-8", reader) if err != nil { fmt.Println(err.Error()) return "request error" } respBytes, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { fmt.Println(err.Error()) return "response error" } return string(respBytes) } func main() { data := make(map[string]TemplateMsgDataItem) data["first"] = TemplateMsgDataItem{Value: "您发布的房源已经上线7天了,请确认房源状态是否已发生变化。"} data["keyword3"] = TemplateMsgDataItem{Value: "金地梅陇镇F栋3001"} data["remark"] = TemplateMsgDataItem{Value: "如房源仍然有效,请忽略本消息。"} msg := TemplateMsg{ToUser: "oAj8Y07DX2guxp-vmtATurBLt9PQ", TemplateId: "GBuf5jfz6oj1YNUaPBpieQrR8IK6cnxiL0BGNZ-bueA", Data: data} // 有屋叽里咕噜爷房源状态更新提醒 bytesData, err := json.Marshal(msg) if err != nil { log.Fatal(err.Error()) return } now := time.Now() n := 1 counter := make(chan bool, n) for i := 0; i < n; i++ { go func(bytes []byte) { respStr := sendTemplateMsg(bytes) //fmt.Println(respStr) if !strings.Contains(respStr, `"errcode":0,"errmsg":"ok"`) { fmt.Println(respStr) } counter <- false }(bytesData) } for i := 0; i < n; i++ { <-counter } fmt.Println("The end") fmt.Println("cost time:", float64(time.Since(now).Nanoseconds())/1000000.0, "ms") }