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.

85 lines
2.1 KiB

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