package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
)
func main() {
//action对应的参数
params := make(map[string]string)
params["Ip"] = "10.10.10.22"
params["Lang"] = "en"
DoAliReq(params)
}
func DoAliReq(uris map[string]string) {
var urlS url.URL
q := urlS.Query()
q.Add("AccessKeyId", "accesskeyid")
q.Add("Timestamp", time.Now().UTC().Format("2006-01-02T15:04:05Z"))
q.Add("Format", "json")
q.Add("SignatureMethod", "HMAC-SHA256")
q.Add("SignatureVersion", "1.0")
q.Add("SignatureNonce", "randommsgid")
q.Add("RegionId", "cn-hangzhou")
q.Add("Version", "2020-01-01")
q.Add("Action", "DescribeIpv4Location") //具体业务action
for k, v := range uris {
q.Add(k, v)
}
sigStr := q.Encode()
strtosign := "GET" + "&" + url.QueryEscape("/") + "&" + url.QueryEscape(sigStr)
sign := Hmacsha256(strtosign, fmt.Sprintf("%v&", "AliKeySecret"))
q.Add("Signature", sign)
url := fmt.Sprintf("http://geoip.aliyuncs.com/?%s", q.Encode())
req, err := http.NewRequest("GET", url, nil)
if nil != err {
fmt.Println(err)
return
}
client := http.DefaultClient
resp, err := client.Do(req)
if nil != err {
fmt.Println(err)
return
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if nil != err {
fmt.Println(err)
return
}
fmt.Println(string(respBody))
return
}
func Hmacsha256(data, key string) (sig string) {
h := hmac.New(sha256.New, []byte(key))
h.Write([]byte(data))
sig = base64.StdEncoding.EncodeToString(h.Sum(nil))
return
}
有疑问加站长微信联系(非本文作者)