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. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "time"
  11. "github.com/tencentyun/cos-go-sdk-v5"
  12. "github.com/tencentyun/cos-go-sdk-v5/debug"
  13. )
  14. func log_status(err error) {
  15. if err == nil {
  16. return
  17. }
  18. if cos.IsNotFoundError(err) {
  19. // WARN
  20. fmt.Println("WARN: Resource is not existed")
  21. } else if e, ok := cos.IsCOSError(err); ok {
  22. fmt.Printf("ERROR: Code: %v\n", e.Code)
  23. fmt.Printf("ERROR: Message: %v\n", e.Message)
  24. fmt.Printf("ERROR: Resource: %v\n", e.Resource)
  25. fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
  26. // ERROR
  27. } else {
  28. fmt.Printf("ERROR: %v\n", err)
  29. // ERROR
  30. }
  31. }
  32. func main() {
  33. ak := os.Getenv("COS_SECRETID")
  34. sk := os.Getenv("COS_SECRETKEY")
  35. u, _ := url.Parse("https://test-1253846586.cos.ap-guangzhou.myqcloud.com")
  36. b := &cos.BaseURL{BucketURL: u}
  37. c := cos.NewClient(b, &http.Client{
  38. Transport: &cos.AuthorizationTransport{
  39. SecretID: ak,
  40. SecretKey: sk,
  41. Expire: time.Hour,
  42. Transport: &debug.DebugRequestTransport{
  43. RequestHeader: true,
  44. RequestBody: true,
  45. ResponseHeader: true,
  46. ResponseBody: true,
  47. },
  48. },
  49. })
  50. name := "test"
  51. ctx := context.Background()
  52. // Normal header way to get object
  53. resp, err := c.Object.Get(ctx, name, nil)
  54. log_status(err)
  55. bs, _ := ioutil.ReadAll(resp.Body)
  56. resp.Body.Close()
  57. // Get presigned
  58. presignedURL, err := c.Object.GetPresignedURL(ctx, http.MethodGet, name, ak, sk, time.Hour, nil)
  59. log_status(err)
  60. // Get object by presinged url
  61. resp2, err := http.Get(presignedURL.String())
  62. log_status(err)
  63. bs2, _ := ioutil.ReadAll(resp2.Body)
  64. resp2.Body.Close()
  65. fmt.Printf("result2 is : %s\n", string(bs2))
  66. fmt.Printf("%v\n\n", bytes.Compare(bs2, bs) == 0)
  67. }