流式下载

更新时间: 2019-03-14 10:05

以下代码展示了如何进行流式下载:

  1. // 引入依赖包
  2. import (
  3. "fmt"
  4. "obs"
  5. )
  6.  
  7. var ak = "*** Provide your Access Key ***"
  8. var sk = "*** Provide your Secret Key ***"
  9. var endpoint = "https://your-endpoint"
  10.  
  11. // 创建ObsClient结构体
  12. var obsClient, _ = obs.New(ak, sk, endpoint)
  13.  
  14. func main() {
  15. input := &obs.GetObjectInput{}
  16. input.Bucket = "bucketname"
  17. input.Key = "objectkey"
  18. output, err := obsClient.GetObject(input)
  19. if err == nil {
  20. defer output.Body.Close()
  21. fmt.Printf("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
  22. output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
  23. p := make([]byte, 1024)
  24. var readErr error
  25. var readCount int
  26. // 读取对象内容
  27. for {
  28. readCount, readErr = output.Body.Read(p)
  29. if readCount > 0 {
  30. fmt.Printf("%s", p[:readCount])
  31. }
  32. if readErr != nil {
  33. break
  34. }
  35. }
  36. } else if obsError, ok := err.(obs.ObsError); ok {
  37. fmt.Printf("Code:%s\n", obsError.Code)
  38. fmt.Printf("Message:%s\n", obsError.Message)
  39. }
  40. }

流式下载 - 图1

GetObjectOutput.Body获取的可读流一定要显式关闭,否则会造成资源泄露。

父主题:下载对象