功能说明
下载一个对象(文件/对象)至本地(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 string}
参数名称 | 参数描述 | 类型 | 是否必选 |
ctx | 请求上下文,用于控制超时与取消 | context.Context | 是 |
name | 对象键(Object Key),即对象在桶中的完整路径 | 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 | 否 |
返回结果说明
参数名称 | 参数描述 | 类型 |
*Response | 响应对象, resp.Body 为对象内容(io.ReadCloser) | *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("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.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))}
注意事项
resp.Body 是 io.ReadCloser,使用完毕后必须调用 Close 释放连接,建议通过 io.ReadAll 读取全部内容。若只需将对象直接落盘到本地文件,可使用
GetToFile。通过
Range 字段可实现分段下载,用于断点续传或部分读取场景。对象键不应以
/ 开头,也不应为空。