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.3 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "net/url"
  7. "strings"
  8. "net/http"
  9. "github.com/tencentyun/cos-go-sdk-v5"
  10. "github.com/tencentyun/cos-go-sdk-v5/debug"
  11. )
  12. func log_status(err error) {
  13. if err == nil {
  14. return
  15. }
  16. if cos.IsNotFoundError(err) {
  17. // WARN
  18. fmt.Println("WARN: Resource is not existed")
  19. } else if e, ok := cos.IsCOSError(err); ok {
  20. fmt.Printf("ERROR: Code: %v\n", e.Code)
  21. fmt.Printf("ERROR: Message: %v\n", e.Message)
  22. fmt.Printf("ERROR: Resource: %v\n", e.Resource)
  23. fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
  24. // ERROR
  25. } else {
  26. fmt.Printf("ERROR: %v\n", err)
  27. // ERROR
  28. }
  29. }
  30. func initUpload(c *cos.Client, name string) *cos.InitiateMultipartUploadResult {
  31. v, _, err := c.Object.InitiateMultipartUpload(context.Background(), name, nil)
  32. log_status(err)
  33. fmt.Printf("%#v\n", v)
  34. return v
  35. }
  36. func main() {
  37. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  38. b := &cos.BaseURL{BucketURL: u}
  39. c := cos.NewClient(b, &http.Client{
  40. Transport: &cos.AuthorizationTransport{
  41. SecretID: os.Getenv("COS_SECRETID"),
  42. SecretKey: os.Getenv("COS_SECRETKEY"),
  43. Transport: &debug.DebugRequestTransport{
  44. RequestHeader: true,
  45. RequestBody: false,
  46. ResponseHeader: true,
  47. ResponseBody: false,
  48. },
  49. },
  50. })
  51. optcom := &cos.CompleteMultipartUploadOptions{}
  52. name := "test/test_multi_upload.go"
  53. up := initUpload(c, name)
  54. uploadID := up.UploadID
  55. fd, err := os.Open("test")
  56. if err != nil {
  57. fmt.Printf("Open File Error: %v\n", err)
  58. return
  59. }
  60. defer fd.Close()
  61. stat, err := fd.Stat()
  62. if err != nil {
  63. fmt.Printf("Stat File Error: %v\n", err)
  64. return
  65. }
  66. opt := &cos.ObjectUploadPartOptions{
  67. Listener: &cos.DefaultProgressListener{},
  68. ContentLength: stat.Size(),
  69. }
  70. resp, err := c.Object.UploadPart(
  71. context.Background(), name, uploadID, 1, fd, opt,
  72. )
  73. log_status(err)
  74. optcom.Parts = append(optcom.Parts, cos.Object{
  75. PartNumber: 1, ETag: resp.Header.Get("ETag"),
  76. })
  77. f := strings.NewReader("test heoo")
  78. resp, err = c.Object.UploadPart(
  79. context.Background(), name, uploadID, 2, f, nil,
  80. )
  81. log_status(err)
  82. optcom.Parts = append(optcom.Parts, cos.Object{
  83. PartNumber: 2, ETag: resp.Header.Get("ETag"),
  84. })
  85. _, _, err = c.Object.CompleteMultipartUpload(context.Background(), name, uploadID, optcom)
  86. log_status(err)
  87. }