功能说明
下载高性能桶中的对象内容(GET Object)。对高性能桶发起下载请求时,SDK 通过
RapidCredentialTransport 自动完成会话鉴权。方法原型
以下展示高性能桶的调用形式,选项与结果结构仅摘录本接口使用的字段。
func (s *ObjectService) Get(ctx context.Context, name string, opt *ObjectGetOptions) (*Response, error)func (s *ObjectService) GetToFile(ctx context.Context, name string, localpath string, opt *ObjectGetOptions) (*Response, error)
参数说明
type ObjectGetOptions struct {ResponseContentType stringResponseContentLanguage stringResponseExpires stringResponseCacheControl stringResponseContentDisposition stringResponseContentEncoding stringRange stringListener ProgressListener}
参数名称 | 参数描述 | 类型 | 是否必选 |
ctx | 请求上下文,用于控制超时与取消 | context.Context | 是 |
name | 对象键(Object Key),即对象在桶中的完整路径 | string | 是 |
localpath | 本地文件路径,仅用于 GetToFile;文件存在时将被覆盖 | string | 是 |
opt | 下载选项,可为 nil | *ObjectGetOptions | 否 |
Range | 指定下载范围,如 bytes=0-1023,用于分段下载 | string | 否 |
ResponseContentType | 指定响应中返回的 Content-Type 头部 | string | 否 |
ResponseContentDisposition | 指定响应中返回的 Content-Disposition 头部 | string | 否 |
ResponseContentEncoding | 指定响应中返回的 Content-Encoding 头部 | string | 否 |
ResponseContentLanguage | 指定响应中返回的 Content-Language 头部 | string | 否 |
ResponseCacheControl | 指定响应中返回的 Cache-Control 头部 | string | 否 |
ResponseExpires | 指定响应中返回的 Expires 头部 | string | 否 |
Listener | 下载进度回调;进度完成不代表接口成功,仍需检查返回的 error | ProgressListener | 否 |
返回结果说明
参数名称 | 参数描述 | 类型 |
*Response | Get 成功时 resp.Body 为待调用方读取和关闭的对象流;GetToFile 已将内容写入本地并关闭响应流,不可再次读取其 Body | *cos.Response |
error | 错误信息,成功时为 nil | error |
使用案例
package mainimport ("context""io""log""net/http""net/url""os""time""github.com/tencentyun/cos-go-sdk-v5")func main() {u, _ := url.Parse("http://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.Get(ctx, name, nil)if err != nil {log.Fatalf("GetObject failed: %v", err)}defer resp.Body.Close()data, err := io.ReadAll(resp.Body)if err != nil {log.Fatalf("read object body failed: %v", err)}log.Printf("GetObject OK, size: %d", len(data))// 也可直接下载到本地文件;已有同名文件将被覆盖。if _, err := c.Object.GetToFile(ctx, name, "downloaded-exampleobject.txt", nil); err != nil {log.Fatalf("GetToFile failed: %v", err)}}
注意事项
Get 返回的 resp.Body 是 io.ReadCloser,使用完毕后必须调用 Close。本文的小对象示例使用 io.ReadAll;大对象请用 io.Copy 流式处理或 GetToFile,避免将完整内容加载到内存。若只需将对象直接落盘到本地文件,可使用
GetToFile。Range 仅用于文件对象,支持 bytes=start-end、bytes=start-、bytes=-length 单一区间;有效范围返回 206,非法范围返回 416 InvalidRange。目录对象携带 Range 返回 400 InvalidArgument。GetToFile 每次都创建或截断目标文件,配合 Range 也不会自动续写;下载失败时可能留下不完整文件。断点续传需由调用方管理本地偏移和写入。对象键不应以
/ 开头,也不应为空。对象键末尾的
/ 严格区分文件对象与目录对象,接口不做容错;类型不匹配时返回 404 NoSuchKey。