功能说明
获取高性能桶当前生效的存储桶策略(GET Bucket Policy)。返回内容为大写 key 的 JSON,Version 固定为 2.0。
方法原型
func (s *BucketService) GetPolicy(ctx context.Context) (*BucketGetPolicyResult, *Response, error)
参数说明
参数名称 | 参数描述 | 类型 | 是否必选 |
ctx | 请求上下文,用于控制超时与取消 | context.Context | 是 |
返回结果说明
BucketGetPolicyResult 与 BucketPutPolicyOptions 字段相同:type BucketGetPolicyResult struct {Statement []BucketStatementVersion stringPrincipal map[string][]string}type BucketStatement struct {Principal map[string][]stringAction []stringEffect stringResource []stringCondition map[string]map[string]interface{}Sid string}
参数名称 | 参数描述 | 类型 |
Version | 策略语法版本,固定为2.0 | string |
Statement | 授权语句列表 | []BucketStatement |
Statement.Action | 授权的操作列表 | []string |
Statement.Effect | 授权效果, allow 或 deny | string |
Statement.Resource | 授权作用的资源,转回 COS 完整桶名形态 | []string |
Statement.Principal | 被授权者 | map[string][]string |
Statement.Sid | 语句标识符 | string |
使用案例
package mainimport ("context""fmt""log""net/http""net/url""os""time""github.com/tencentyun/cos-go-sdk-v5")func main() {u, _ := url.Parse("https://examplebucket-x--1250000000.cosrapid.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}base := &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"),SecretKey: os.Getenv("SECRETKEY"),}c := cos.NewClient(b, &http.Client{Transport: cos.NewRapidCredentialTransport(base),Timeout: 30 * time.Second,})ctx := context.Background()res, _, err := c.Bucket.GetPolicy(ctx)if err != nil {log.Fatalf("GetPolicy failed: %v", err)}fmt.Printf("Version: %s\\n", res.Version)for _, stmt := range res.Statement {fmt.Printf("Sid: %s, Effect: %s, Action: %v, Resource: %v\\n",stmt.Sid, stmt.Effect, stmt.Action, stmt.Resource)}}
注意事项
当桶上未设置任何策略时,
GetPolicy 会返回错误,对应 404 NoSuchPolicy,可通过错误码或 IsNotFoundError 判断。错误处理方式请参见 异常处理。