功能说明
查询高性能桶中对象的元数据,不返回对象内容(HEAD Object)。元数据通过响应头部返回。对高性能桶发起请求时,SDK 通过
RapidCredentialTransport 自动完成会话鉴权。方法原型
func (s *ObjectService) Head(ctx context.Context, name string, opt *ObjectHeadOptions) (*Response, error)
参数说明
参数名称 | 参数描述 | 类型 | 是否必选 |
ctx | 请求上下文,用于控制超时与取消 | context.Context | 是 |
name | 对象键(Object Key),即对象在桶中的完整路径 | string | 是 |
opt | 查询选项,高性能桶无额外可选项,传 nil 即可 | *ObjectHeadOptions | 否 |
返回结果说明
对象元数据从
resp.Header 中读取,常见头部:头部 | 参数描述 | 类型 |
Content-Length | 对象内容长度(字节) | string |
Content-Type | 对象的 MIME 类型 | string |
ETag | 对象的 ETag | string |
Last-Modified | 对象的最后修改时间 | string |
x-cos-meta-* | 用户自定义元数据 | string |
参数名称 | 参数描述 | 类型 |
*Response | 响应对象,元数据通过 resp.Header 返回 | *cos.Response |
error | 错误信息,成功时为 nil | error |
使用案例
package mainimport ("context""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()name := "exampleobject.txt"resp, err := c.Object.Head(ctx, name, nil)if err != nil {log.Fatalf("HeadObject failed: %v", err)}log.Printf("Content-Length: %s", resp.Header.Get("Content-Length"))log.Printf("ETag: %s", resp.Header.Get("ETag"))}
注意事项
Head 请求不返回对象内容,所有元数据均从
resp.Header 中读取。若仅需判断对象是否存在,可使用
IsExist:func (s *ObjectService) IsExist(ctx context.Context, name string) (bool, error),它会屏蔽 NotFound 错误并直接返回布尔结果。对象键不应以
/ 开头,也不应为空。