4 Star 5 Fork 4

Plato/Service-Box-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
auth.go 1.66 KB
一键复制 编辑 原始数据 按行查看 历史
package apollo
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"net/url"
"strconv"
"time"
)
// HTTPAuth http 授权
type HTTPAuth interface {
// HTTPHeaders 根据 @url 获取 http 授权请求头
HTTPHeaders(url string, appID string, secret string) map[string][]string
}
const (
httpHeaderAuthorization = "Authorization"
httpHeaderTimestamp = "Timestamp"
authorizationFormat = "Apollo %s:%s"
delimiter = "\n"
question = "?"
)
// AuthSignature apollo 授权
type AuthSignature struct {
}
// HTTPHeaders HTTPHeaders
func (t *AuthSignature) HTTPHeaders(url string, appID string, secret string) map[string][]string {
ms := time.Now().UnixNano() / int64(time.Millisecond)
timestamp := strconv.FormatInt(ms, 10)
pathWithQuery := url2PathWithQuery(url)
stringToSign := timestamp + delimiter + pathWithQuery
signature := signString(stringToSign, secret)
headers := make(map[string][]string, 2)
signatures := make([]string, 0, 1)
signatures = append(signatures, fmt.Sprintf(authorizationFormat, appID, signature))
headers[httpHeaderAuthorization] = signatures
timestamps := make([]string, 0, 1)
timestamps = append(timestamps, timestamp)
headers[httpHeaderTimestamp] = timestamps
return headers
}
func signString(stringToSign string, accessKeySecret string) string {
key := []byte(accessKeySecret)
mac := hmac.New(sha1.New, key)
mac.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func url2PathWithQuery(rawURL string) string {
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
pathWithQuery := u.Path
if len(u.RawQuery) > 0 {
pathWithQuery += question + u.RawQuery
}
return pathWithQuery
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dennis-kk/service-box-go.git
git@gitee.com:dennis-kk/service-box-go.git
dennis-kk
service-box-go
Service-Box-go
v0.4.30

搜索帮助