@@ -14,6 +14,7 @@ import (
1414 api "github.com/qiniu/go-sdk/v7"
1515 "github.com/qiniu/go-sdk/v7/conf"
1616 internal_io "github.com/qiniu/go-sdk/v7/internal/io"
17+ "github.com/qiniu/go-sdk/v7/storagev2/defaults"
1718)
1819
1920const (
@@ -32,18 +33,39 @@ type Credentials struct {
3233 SecretKey []byte
3334}
3435
35- // 构建一个Credentials对象
36+ // New 构建一个Credentials对象
3637func New (accessKey , secretKey string ) * Credentials {
3738 return & Credentials {accessKey , []byte (secretKey )}
3839}
3940
41+ // Default 构建默认的 Credentials 对象
42+ func Default () * Credentials {
43+ accessKey , secretKey , err := defaults .Credentials ()
44+ if err == nil && accessKey != "" && secretKey != "" {
45+ return New (accessKey , secretKey )
46+ }
47+ return nil
48+ }
49+
4050// Sign 对数据进行签名,一般用于私有空间下载用途
4151func (ath * Credentials ) Sign (data []byte ) (token string ) {
42- h := hmac .New (sha1 .New , ath .SecretKey )
52+ var (
53+ accessKey string
54+ secretKey []byte
55+ )
56+ if ath == nil {
57+ if cred := Default (); cred != nil {
58+ accessKey = cred .AccessKey
59+ secretKey = cred .SecretKey
60+ }
61+ } else {
62+ accessKey , secretKey = ath .AccessKey , ath .SecretKey
63+ }
64+ h := hmac .New (sha1 .New , secretKey )
4365 h .Write (data )
4466
4567 sign := base64 .URLEncoding .EncodeToString (h .Sum (nil ))
46- return fmt .Sprintf ("%s:%s" , ath . AccessKey , sign )
68+ return fmt .Sprintf ("%s:%s" , accessKey , sign )
4769}
4870
4971// SignToken 根据t的类型对请求进行签名,并把token加入req中
@@ -74,8 +96,16 @@ func (ath *Credentials) SignWithData(b []byte) (token string) {
7496
7597// IsIAMKey 判断AccessKey是否为IAM的Key
7698func (ath * Credentials ) IsIAMKey () bool {
77- return len (ath .AccessKey ) == IAMKeyLen * 4 / 3 &&
78- strings .HasPrefix (ath .AccessKey , IAMKeyPrefix )
99+ var accessKey string
100+ if ath == nil {
101+ if cred := Default (); cred != nil {
102+ accessKey = cred .AccessKey
103+ }
104+ } else {
105+ accessKey = ath .AccessKey
106+ }
107+ return len (accessKey ) == IAMKeyLen * 4 / 3 &&
108+ strings .HasPrefix (accessKey , IAMKeyPrefix )
79109}
80110
81111func collectData (req * http.Request ) (data []byte , err error ) {
0 commit comments