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.

77 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. SecretID: ak,
  21. SecretKey: sk,
  22. Transport: &debug.DebugRequestTransport{
  23. RequestHeader: true,
  24. RequestBody: true,
  25. ResponseHeader: true,
  26. ResponseBody: true,
  27. },
  28. },
  29. })
  30. // Case1 Download object into ReadCloser(). the body needs to be closed
  31. name := "test/hello.txt"
  32. resp, err := c.Object.Get(context.Background(), name, nil)
  33. if err != nil {
  34. panic(err)
  35. }
  36. bs, _ := ioutil.ReadAll(resp.Body)
  37. resp.Body.Close()
  38. fmt.Printf("%s\n", string(bs))
  39. // Case2 Download object to local file. the body needs to be closed
  40. fd, err := os.OpenFile("hello.txt", os.O_WRONLY|os.O_CREATE, 0660)
  41. if err != nil {
  42. panic(err)
  43. }
  44. defer fd.Close()
  45. resp, err = c.Object.Get(context.Background(), name, nil)
  46. if err != nil {
  47. panic(err)
  48. }
  49. io.Copy(fd, resp.Body)
  50. resp.Body.Close()
  51. // Case3 Download object to local file path
  52. err = c.Object.GetToFile(context.Background(), name, "hello_1.txt", nil)
  53. if err != nil {
  54. panic(err)
  55. }
  56. // Case4 Download object with range header, can used to concurrent download
  57. opt := &cos.ObjectGetOptions{
  58. ResponseContentType: "text/html",
  59. Range: "bytes=0-3",
  60. }
  61. resp, err = c.Object.Get(context.Background(), name, opt)
  62. if err != nil {
  63. panic(err)
  64. }
  65. bs, _ = ioutil.ReadAll(resp.Body)
  66. resp.Body.Close()
  67. fmt.Printf("%s\n", string(bs))
  68. }