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.

73 lines
1.7 KiB

4 years ago
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "os"
  8. "sync"
  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 upload(wg *sync.WaitGroup, c *cos.Client, files <-chan string) {
  31. defer wg.Done()
  32. for file := range files {
  33. name := "test/" + file
  34. _, _, err := c.Object.Upload(context.Background(), name, file, nil)
  35. if err != nil {
  36. log_status(err)
  37. }
  38. }
  39. }
  40. func main() {
  41. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  42. b := &cos.BaseURL{BucketURL: u}
  43. c := cos.NewClient(b, &http.Client{
  44. Transport: &cos.AuthorizationTransport{
  45. SecretID: os.Getenv("COS_SECRETID"),
  46. SecretKey: os.Getenv("COS_SECRETKEY"),
  47. Transport: &debug.DebugRequestTransport{
  48. RequestHeader: true,
  49. // Notice when put a large file and set need the request body, might happend out of memory error.
  50. RequestBody: false,
  51. ResponseHeader: true,
  52. ResponseBody: false,
  53. },
  54. },
  55. })
  56. filesCh := make(chan string, 2)
  57. filePaths := []string{"test1", "test2", "test3"}
  58. var wg sync.WaitGroup
  59. threadpool := 2
  60. for i := 0; i < threadpool; i++ {
  61. wg.Add(1)
  62. go upload(&wg, c, filesCh)
  63. }
  64. for _, filePath := range filePaths {
  65. filesCh <- filePath
  66. }
  67. close(filesCh)
  68. wg.Wait()
  69. }