delete_object.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package sample
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  6. )
  7. // DeleteObjectSample 展示了删除单个文件、批量删除文件的方法
  8. func DeleteObjectSample() {
  9. // 创建Bucket
  10. bucket, err := GetTestBucket(bucketName)
  11. if err != nil {
  12. HandleError(err)
  13. }
  14. var val = "抽刀断水水更流,举杯销愁愁更愁。 人生在世不称意,明朝散发弄扁舟。"
  15. // 场景1:删除Object
  16. err = bucket.PutObject(objectKey, strings.NewReader(val))
  17. if err != nil {
  18. HandleError(err)
  19. }
  20. err = bucket.DeleteObject(objectKey)
  21. if err != nil {
  22. HandleError(err)
  23. }
  24. // 场景2:删除多个Object
  25. err = bucket.PutObject(objectKey+"1", strings.NewReader(val))
  26. if err != nil {
  27. HandleError(err)
  28. }
  29. err = bucket.PutObject(objectKey+"2", strings.NewReader(val))
  30. if err != nil {
  31. HandleError(err)
  32. }
  33. delRes, err := bucket.DeleteObjects([]string{objectKey + "1", objectKey + "2"})
  34. if err != nil {
  35. HandleError(err)
  36. }
  37. fmt.Println("Del Res:", delRes)
  38. lsRes, err := bucket.ListObjects()
  39. if err != nil {
  40. HandleError(err)
  41. }
  42. fmt.Println("Objects:", getObjectsFormResponse(lsRes))
  43. // 场景3:删除多个Object,详细模式时返回的结果中会包含成功删除的Object,默认该模式
  44. err = bucket.PutObject(objectKey+"1", strings.NewReader(val))
  45. if err != nil {
  46. HandleError(err)
  47. }
  48. err = bucket.PutObject(objectKey+"2", strings.NewReader(val))
  49. if err != nil {
  50. HandleError(err)
  51. }
  52. delRes, err = bucket.DeleteObjects([]string{objectKey + "1", objectKey + "2"},
  53. oss.DeleteObjectsQuiet(false))
  54. if err != nil {
  55. HandleError(err)
  56. }
  57. fmt.Println("Detail Del Res:", delRes)
  58. lsRes, err = bucket.ListObjects()
  59. if err != nil {
  60. HandleError(err)
  61. }
  62. fmt.Println("Objects:", getObjectsFormResponse(lsRes))
  63. // 场景4:删除多个Object,简单模式返回的消息体中只包含删除出错的Object结果
  64. err = bucket.PutObject(objectKey+"1", strings.NewReader(val))
  65. if err != nil {
  66. HandleError(err)
  67. }
  68. err = bucket.PutObject(objectKey+"2", strings.NewReader(val))
  69. if err != nil {
  70. HandleError(err)
  71. }
  72. delRes, err = bucket.DeleteObjects([]string{objectKey + "1", objectKey + "2"}, oss.DeleteObjectsQuiet(true))
  73. if err != nil {
  74. HandleError(err)
  75. }
  76. fmt.Println("Sample Del Res:", delRes)
  77. lsRes, err = bucket.ListObjects()
  78. if err != nil {
  79. HandleError(err)
  80. }
  81. fmt.Println("Objects:", getObjectsFormResponse(lsRes))
  82. // 删除object和bucket
  83. err = DeleteTestBucketAndObject(bucketName)
  84. if err != nil {
  85. HandleError(err)
  86. }
  87. fmt.Println("DeleteObjectSample completed")
  88. }