tencent/COS.go
2024-12-20 18:35:59 +08:00

63 lines
1.4 KiB
Go

package tencent
import (
"strings"
sts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
)
func getCosClient(bucket string) *sts.Client {
return sts.NewClient(conf.Cos[bucket].SecretId, conf.Cos[bucket].SecretKey, nil)
}
type Cos struct {
client *sts.Client
bucket string
appId string
region string
}
func GetCos(bucket string) *Cos {
bConf := conf.Cos[bucket]
a := strings.Split(bConf.Bucket, "-")
return &Cos{
client: getCosClient(bucket),
bucket: bConf.Bucket,
appId: a[len(a)-1],
region: bConf.Region,
}
}
type CosToken struct {
sts.Credentials
Bucket string
Region string
}
var defaultAllowPath = "/"
func (c *Cos) GetToken(allowPath *string) (*CosToken, error) {
if allowPath == nil {
allowPath = &defaultAllowPath
}
crt, err := c.client.GetCredential(&sts.CredentialOptions{
DurationSeconds: 3600,
Region: c.region,
Policy: &sts.CredentialPolicy{
Statement: []sts.CredentialPolicyStatement{{
Action: []string{"name/cos:PostObject", "name/cos:PutObject", "name/cos:InitiateMultipartUpload", "name/cos:ListMultipartUploads", "name/cos:ListParts", "name/cos:UploadPart", "name/cos:CompleteMultipartUpload"},
Effect: "allow",
Resource: []string{"qcs::cos:" + c.region + ":uid/" + c.appId + ":" + c.bucket + *allowPath + "*"},
}},
},
})
if err == nil {
return &CosToken{
Credentials: *crt.Credentials,
Bucket: c.bucket,
Region: c.region,
}, nil
}
return nil, err
}