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.

80 lines
2.0 KiB

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. "net/url"
  6. "os"
  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 main() {
  31. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  32. b := &cos.BaseURL{BucketURL: u}
  33. c := cos.NewClient(b, &http.Client{
  34. Transport: &cos.AuthorizationTransport{
  35. SecretID: os.Getenv("COS_SECRETID"),
  36. SecretKey: os.Getenv("COS_SECRETKEY"),
  37. Transport: &debug.DebugRequestTransport{
  38. RequestHeader: true,
  39. // Notice when put a large file and set need the request body, might happend out of memory error.
  40. RequestBody: false,
  41. ResponseHeader: true,
  42. ResponseBody: false,
  43. },
  44. },
  45. })
  46. // Case1 上传对象
  47. name := "test/example"
  48. f := strings.NewReader("test")
  49. _, err := c.Object.Put(context.Background(), name, f, nil)
  50. log_status(err)
  51. // Case2 使用options上传对象
  52. f = strings.NewReader("test xxx")
  53. opt := &cos.ObjectPutOptions{
  54. ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
  55. ContentType: "text/html",
  56. },
  57. ACLHeaderOptions: &cos.ACLHeaderOptions{
  58. //XCosACL: "public-read",
  59. XCosACL: "private",
  60. },
  61. }
  62. _, err = c.Object.Put(context.Background(), name, f, opt)
  63. log_status(err)
  64. // Case3 通过本地文件上传对象
  65. _, err = c.Object.PutFromFile(context.Background(), name, "./test", nil)
  66. log_status(err)
  67. // Case4 查看上传进度
  68. opt.ObjectPutHeaderOptions.Listener = &cos.DefaultProgressListener{}
  69. _, err = c.Object.PutFromFile(context.Background(), name, "./test", opt)
  70. }