7
0
gaore-common-sdk-go/sdk/auth/http_build_param.go
2020-08-06 10:35:24 +08:00

57 lines
1.7 KiB
Go

package auth
import (
"bytes"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/utils"
"net/url"
"strings"
"time"
)
func signHttpRequest(request requests.AcsRequest, signer Signer) (err error) {
err = completeHttpSignParams(request, signer)
if err != nil {
return
}
if _, isContainsSign := request.GetQueryParams()["sign"]; isContainsSign {
delete(request.GetQueryParams(), "sign")
}
stringToSign := buildHttpStringToSign(request)
request.SetStringToSign(stringToSign)
signature := signer.Sign(stringToSign, "&")
request.GetQueryParams()["sign"] = signature
return
}
func completeHttpSignParams(request requests.AcsRequest, signer Signer) (err error) {
queryParams := request.GetQueryParams()
queryParams["timestamp"] = fmt.Sprintf("%d", time.Now().Unix())
queryParams["access_key"], err = signer.GetAccessKeyId()
request.GetHeaders()["Content-type"] = requests.Form
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent(bytes.NewBufferString(formString).Bytes())
return
}
func buildHttpStringToSign(request requests.AcsRequest) (stringToSign string) {
signParams := make(map[string]string)
for key, value := range request.GetQueryParams() {
signParams[key] = value
}
for key, value := range request.GetFormParams() {
signParams[key] = value
}
stringToSign = utils.GetUrlFormedMap(signParams)
stringToSign = strings.Replace(stringToSign, "+", "%20", -1)
stringToSign = strings.Replace(stringToSign, "*", "%2A", -1)
stringToSign = strings.Replace(stringToSign, "%7E", "~", -1)
stringToSign = url.QueryEscape(stringToSign)
stringToSign = request.GetMethod() + "&%2F&" + stringToSign
return
}