最近更新时间:2024-08-12 10:30:24
引入
go get "github.com/aws/aws-sdk-go"
Go AWS签名DEMO
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
)
func main() {
ak := "Your AK" //请替换为您的AccessKey
sk := "Your SK" //请替换为您的SecretKey
service := "iam" //访问的服务
region := "cn-beijing-6" //访问的区域
creds := credentials.NewStaticCredentials(ak, sk, "")
signer := v4.NewSigner(creds)
params := map[string]string{
//固定参数
"Action": "ListUsers", //接口名称
"Version": "2015-11-01", //接口版本
//接口参数
"Marker": "1",
"MaxItems": "100",
}
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var queryString strings.Builder
for _, k := range keys {
queryString.WriteString(k + "=" + url.QueryEscape(params[k]) + "&")
}
queryStringStr := strings.TrimSuffix(queryString.String(), "&")
req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s.api.ksyun.com?%s", service, queryStringStr), nil)
req.Header.Set("Accept", "application/json")
req.Host = fmt.Sprintf("%s.api.ksyun.com", service)
_, err := signer.Sign(req, nil, service, region, time.Now())
if err != nil {
panic(err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
}
纯净模式