功能说明
为高性能桶创建访问会话(CreateSession),返回可用于后续请求的临时凭证,是高性能桶专属能力。在使用 Go SDK 访问高性能桶时,
RapidCredentialTransport 会自动调用本接口并缓存复用临时凭证,通常无需手动调用;本文档说明其手动调用方式及返回结构,便于需要自行管理临时凭证的场景使用。方法原型
func (s *BucketService) CreateSession(ctx context.Context) (*CreateSessionResult, *Response, error)
参数说明
参数名称 | 参数描述 | 类型 | 是否必选 |
ctx | 请求上下文,用于控制超时与取消 | context.Context | 是 |
会话的读写模式(ReadWrite / ReadOnly)由服务端根据调用方在 CAM / 桶策略中被授予的权限自动决定,Go SDK 不通过入参指定。
返回结果说明
type CreateSessionResult struct {Credentials SessionCredential}type SessionCredential struct {SecretID stringSecretKey stringSessionToken stringExpiration time.Time}
参数名称 | 参数描述 | 类型 |
Credentials.SecretID | 临时凭证 AccessKeyId(临时 SecretId) | string |
Credentials.SecretKey | 临时凭证 SecretAccessKey(临时 SecretKey) | string |
Credentials.SessionToken | 会话令牌,后续请求需携带 | string |
Credentials.Expiration | 临时凭证过期时间 | time.Time |
使用案例
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.CreateSession(ctx)if err != nil {log.Fatalf("CreateSession failed: %v", err)}cred := res.Credentialsfmt.Printf("AccessKeyId: %s\\n", cred.SecretID)fmt.Printf("SessionToken: %s\\n", cred.SessionToken)fmt.Printf("Expiration: %s\\n", cred.Expiration.Format(time.RFC3339))}
注意事项
临时凭证具有桶级作用域,仅对创建会话时指定的高性能桶有效。
临时凭证有效期较短,过期后需重新创建会话。使用
RapidCredentialTransport 时,SDK 会在凭证接近过期时自动重新签发。若返回的凭证不完整或过期时间缺失/非法,SDK 会直接返回错误,不会下发无效凭证。