本文档提供快捷查询存储桶中某个对象是否存在的示例代码。
示例代码实际调用了 COS API HeadObject,是该接口的简化版。
HeadObject 除了检查对象是否存在,主要功能为返回对象元数据。包含了 HeadObject 完整功能的 SDK 接口,可参见 查询对象元数据。
您可以通过 SDK 提供的快捷接口来检查对象是否存在。
注意:COS Go SDK 版本需要大于等于 v0.7.33。
func (s *ObjectService) IsExist(ctx context.Context, key string, id ...string) (isExist bool, err error)
package main
import (
"context"
"fmt"
"github.com/tencentyun/cos-go-sdk-v5"
"net/http"
"net/url"
"os"
)
func main() {
// 存储桶名称,由bucketname-appid 组成,appid必须填入,可以在COS控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
// 替换为用户的 region,存储桶region可以在COS控制台“存储桶概览”查看 https://console.cloud.tencent.com/ ,关于地域的详情见 https://intl.cloud.tencent.com/document/product/436/6224?from_cn_redirect=1 。
u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}
client := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
// 通过环境变量获取密钥
// 环境变量 SECRETID 表示用户的 SecretId,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
SecretID: os.Getenv("SECRETID"),
// 环境变量 SECRETKEY 表示用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
SecretKey: os.Getenv("SECRETKEY"),
},
})
key := "exampleobject"
ok, err := client.Object.IsExist(context.Background(), key)
if err == nil && ok {
fmt.Printf("object exists\n")
} else if err != nil {
fmt.Printf("head object failed: %v\n", err)
} else {
fmt.Printf("object does not exist\n")
}
}
参数名称 | 描述 | 类型 | 是否必填 |
---|---|---|---|
key | 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg 中,对象键为 doc/pic.jpg |
string | 是 |
id | 对象 VersionId。 | string | 否 |
参数名称 | 描述 | 类型 |
---|---|---|
isExist | 对象是否存在 | bool |
err | 请求是否成功 | struct |
本页内容是否解决了您的问题?