最近更新时间:2024-08-12 10:30:24
Go签名DEMO如下:
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
// 简易签名函数,使用HMAC-SHA256算法
func Sign(params map[string]string, secretKey string) string {
//对参数键进行排序
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
//构建待签名字符串
var strEncode string
for _, k := range keys {
strEncode += url.QueryEscape(k) + "=" + url.QueryEscape(params[k]) + "&"
}
strEncode = strEncode[:len(strEncode)-1]
//生成HMAC-SHA256签名
h := hmac.New(sha256.New, []byte(secretKey))
h.Write([]byte(strEncode))
return hex.EncodeToString(h.Sum(nil))
}
func main() {
ak := "Your AK" //请替换为您的AccessKey
sk := "Your SK" //请替换为您的SecretKey
service := "iam" //访问的服务
region := "cn-beijing-6" //访问的区域
params := map[string]string{
//固定参数
"Accesskey": ak,
"Service": service,
"Region": region,
"Action": "ListUsers", //接口名称
"Version": "2015-11-01", //接口版本
"Timestamp": time.Now().UTC().Format("2006-01-02T15:04:05Z"),
"SignatureVersion": "1.0",
"SignatureMethod": "HMAC-SHA256",
//接口参数
"Marker": "1",
"MaxItems": "100",
}
signature := Sign(params, sk)
var requestURL strings.Builder
requestURL.WriteString(fmt.Sprintf("http://%s.api.ksyun.com/?", service))
for k, v := range params {
requestURL.WriteString(k + "=" + v + "&")
}
requestURL.WriteString("Signature=" + signature)
headers := map[string]string{
"Accept": "application/json",
}
client := &http.Client{}
req, _ := http.NewRequest("GET", requestURL.String(), nil)
for k, v := range headers {
req.Header.Add(k, v)
}
req.Host = fmt.Sprintf("%s.api.ksyun.com", service)
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Body:", string(body))
}
纯净模式
鼠标选中内容,快速反馈问题