You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.7 KiB

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/url"
  6. "os"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "github.com/tencentyun/cos-go-sdk-v5"
  11. "github.com/tencentyun/cos-go-sdk-v5/debug"
  12. )
  13. func main() {
  14. u, _ := url.Parse("https://test-1253846586.cos.ap-guangzhou.myqcloud.com")
  15. b := &cos.BaseURL{BucketURL: u}
  16. c := cos.NewClient(b, &http.Client{
  17. Transport: &cos.AuthorizationTransport{
  18. SecretID: os.Getenv("COS_SECRETID"),
  19. SecretKey: os.Getenv("COS_SECRETKEY"),
  20. Transport: &debug.DebugRequestTransport{
  21. RequestHeader: true,
  22. RequestBody: true,
  23. ResponseHeader: true,
  24. ResponseBody: false,
  25. },
  26. },
  27. })
  28. // Case1 Download object into ReadCloser(). the body needs to be closed
  29. name := "test/hello.txt"
  30. resp, err := c.Object.Get(context.Background(), name, nil)
  31. if err != nil {
  32. panic(err)
  33. }
  34. bs, _ := ioutil.ReadAll(resp.Body)
  35. resp.Body.Close()
  36. fmt.Printf("%s\n", string(bs))
  37. // Case2 Download object to local file. the body needs to be closed
  38. fd, err := os.OpenFile("hello.txt", os.O_WRONLY|os.O_CREATE, 0660)
  39. if err != nil {
  40. panic(err)
  41. }
  42. defer fd.Close()
  43. resp, err = c.Object.Get(context.Background(), name, nil)
  44. if err != nil {
  45. panic(err)
  46. }
  47. io.Copy(fd, resp.Body)
  48. resp.Body.Close()
  49. // Case3 Download object to local file path
  50. err = c.Object.GetToFile(context.Background(), name, "hello_1.txt", nil)
  51. if err != nil {
  52. panic(err)
  53. }
  54. // Case4 Download object with range header, can used to concurrent download
  55. opt := &cos.ObjectGetOptions{
  56. ResponseContentType: "text/html",
  57. Range: "bytes=0-3",
  58. }
  59. resp, err = c.Object.Get(context.Background(), name, opt)
  60. if err != nil {
  61. panic(err)
  62. }
  63. bs, _ = ioutil.ReadAll(resp.Body)
  64. resp.Body.Close()
  65. fmt.Printf("%s\n", string(bs))
  66. }