流式下载
更新时间: 2019-03-14 10:05
以下代码展示了如何进行流式下载:
- // 引入依赖包
- import (
- "fmt"
- "obs"
- )
- var ak = "*** Provide your Access Key ***"
- var sk = "*** Provide your Secret Key ***"
- var endpoint = "https://your-endpoint"
- // 创建ObsClient结构体
- var obsClient, _ = obs.New(ak, sk, endpoint)
- func main() {
- input := &obs.GetObjectInput{}
- input.Bucket = "bucketname"
- input.Key = "objectkey"
- output, err := obsClient.GetObject(input)
- if err == nil {
- defer output.Body.Close()
- fmt.Printf("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
- output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
- p := make([]byte, 1024)
- var readErr error
- var readCount int
- // 读取对象内容
- for {
- readCount, readErr = output.Body.Read(p)
- if readCount > 0 {
- fmt.Printf("%s", p[:readCount])
- }
- if readErr != nil {
- break
- }
- }
- } else if obsError, ok := err.(obs.ObsError); ok {
- fmt.Printf("Code:%s\n", obsError.Code)
- fmt.Printf("Message:%s\n", obsError.Message)
- }
- }
GetObjectOutput.Body获取的可读流一定要显式关闭,否则会造成资源泄露。
父主题:下载对象