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.

98 lines
2.2 KiB

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "net/url"
  7. "os"
  8. "strings"
  9. "net/http"
  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 initUpload(c *cos.Client, name string) *cos.InitiateMultipartUploadResult {
  32. v, _, err := c.Object.InitiateMultipartUpload(context.Background(), name, nil)
  33. log_status(err)
  34. fmt.Printf("%#v\n", v)
  35. return v
  36. }
  37. func uploadPart(c *cos.Client, name string, uploadID string, blockSize, n int) string {
  38. b := make([]byte, blockSize)
  39. if _, err := rand.Read(b); err != nil {
  40. log_status(err)
  41. }
  42. s := fmt.Sprintf("%X", b)
  43. f := strings.NewReader(s)
  44. resp, err := c.Object.UploadPart(
  45. context.Background(), name, uploadID, n, f, nil,
  46. )
  47. log_status(err)
  48. fmt.Printf("%s\n", resp.Status)
  49. return resp.Header.Get("Etag")
  50. }
  51. func main() {
  52. u, _ := url.Parse("http://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  53. b := &cos.BaseURL{BucketURL: u}
  54. c := cos.NewClient(b, &http.Client{
  55. Transport: &cos.AuthorizationTransport{
  56. SecretID: os.Getenv("COS_SECRETID"),
  57. SecretKey: os.Getenv("COS_SECRETKEY"),
  58. Transport: &debug.DebugRequestTransport{
  59. RequestHeader: true,
  60. RequestBody: false,
  61. ResponseHeader: true,
  62. ResponseBody: true,
  63. },
  64. },
  65. })
  66. name := "test/test_list_parts.go"
  67. up := initUpload(c, name)
  68. uploadID := up.UploadID
  69. blockSize := 1024 * 1024 * 3
  70. for i := 1; i < 5; i++ {
  71. uploadPart(c, name, uploadID, blockSize, i)
  72. }
  73. opt := &cos.ObjectListUploadsOptions{
  74. Prefix: cos.EncodeURIComponent("test/test_list_parts"),
  75. MaxUploads: 100,
  76. }
  77. v, _, err := c.Object.ListUploads(context.Background(), opt)
  78. if err != nil {
  79. log_status(err)
  80. return
  81. }
  82. fmt.Printf("%+v\n", v)
  83. for _, p := range v.Upload {
  84. fmt.Printf("%+v\n", p)
  85. fmt.Printf("%v, %v, %v\n", p.Key, p.UploadID, p.Initiated)
  86. }
  87. }