寫的比較粗糙,有錯誤的地方希望指正,不會英語,部分變數用拼音命名,打擾了
package sendmsgimport ( "bytes" "crypto/hmac" "crypto/sha1" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time")const ( ak = "xxxxxxx" sk = "xxxxxxx" requestURL = "http://dysmsapi.aliyuncs.com/?Signature=" actionStr = "&Action=SendSms&Format=JSON&OutId=123" dateStr = "&Version=2017-05-25" msgTemplete = "&SignatureVersion=1.0&TemplateCode=模板ID&TemplateParam=" singStr = "&SignatureMethod=HMAC-SHA1&SignatureNonce=" singName = "&RegionId=cn-hangzhou&SignName=" lianJIe = "&" signLinaJie = "GET&%2F&")//SimpleMessage ...type SimpleMessage struct { Message string `json:"Message"` Code string `json:"Code"`}//MessageContent ...type MessageContent struct { Code string `json:"code"`}//SendMsg 傳送簡訊func SendMsg(phone, msgJSON string) bool { body := "send msg" content := url.QueryEscape(msgJSON) signString := setQueryStr(phone, content, “skw493jei3j34ij34i”) singstr := signLinaJie + url.QueryEscape(signString) sign := hmac4Go(singstr, sk+lianJIe) client := &http.Client{} var req *http.Request req, err = http.NewRequest("GET", requestURL+url.QueryEscape(sign)+lianJIe+signString, strings.NewReader(body)) var resp *http.Response resp, err = client.Do(req) if err != nil { fmt.Println("http get error.", err) return false } fmt.Println(resp.Body) defer resp.Body.Close() var bodys []byte bodys, err = ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("http readAll body error ", err) return false } fmt.Println(string(bodys)) var msg SimpleMessage if len(bodys) > 0 { err = json.Unmarshal(bodys, &msg) if err != nil { fmt.Println("http json body error ", err) return false } fmt.Println(msg) } if msg.Code == "OK" { return true } return false}//setQueryStr 設定查詢請求func setQueryStr(phone, content string, id int64) string { var cstZone = time.FixedZone("GMT", 0) keyTime := time.Now().In(cstZone).Format("2006-01-02T15:04:05Z") singNameS := url.QueryEscape("SignName") buf := bytes.Buffer{} buf.WriteString("AccessKeyId=") buf.WriteString(ak) buf.WriteString(actionStr) buf.WriteString("&PhoneNumbers=") buf.WriteString(phone + singName + singNameS + singStr) buf.WriteString(strconv.FormatInt(id, 10) + msgTemplete + content) buf.WriteString("&Timestamp=" + url.QueryEscape(keyTime) + dateStr) signString := buf.String() return signString}//hmac4Go 加密func hmac4Go(name, sk string) string { mac := hmac.New(sha1.New, []byte(sk)) mac.Write([]byte(name)) encodeString := base64.StdEncoding.EncodeToString(mac.Sum(nil)) return encodeString}