删除对象

更新时间: 2019-03-14 10:05

删除单个对象

您可以通过ObsClient.DeleteObject删除单个对象。以下代码展示如何删除单个对象:

  1. // 引入依赖包
  2. import (
  3. "fmt"
  4. "obs"
  5. )
  6.  
  7. var ak = "*** Provide your Access Key ***"
  8. var sk = "*** Provide your Secret Key ***"
  9. var endpoint = "https://your-endpoint"
  10.  
  11. // 创建ObsClient结构体
  12. var obsClient, _ = obs.New(ak, sk, endpoint)
  13.  
  14. func main() {
  15. input := &obs.DeleteObjectInput{}
  16. input.Bucket = "bucketname"
  17. input.Key = "objectkey"
  18.  
  19. output, err := obsClient.DeleteObject(input)
  20. if err == nil {
  21. fmt.Printf("RequestId:%s\n", output.RequestId)
  22. } else if obsError, ok := err.(obs.ObsError); ok {
  23. fmt.Printf("Code:%s\n", obsError.Code)
  24. fmt.Printf("Message:%s\n", obsError.Message)
  25. }
  26. }

批量删除对象

您可以通过ObsClient.DeleteObjects批量删除对象。

每次最多删除1000个对象,并支持两种响应模式:详细(verbose)模式和简单(quiet)模式。

  • 详细模式:返回的删除成功和删除失败的所有结果,默认模式。
  • 简单模式:只返回的删除过程中出错的结果。

以下代码展示了如何进行批量删除对象:

  1. // 引入依赖包
  2. import (
  3. "fmt"
  4. "obs"
  5. )
  6.  
  7. var ak = "*** Provide your Access Key ***"
  8. var sk = "*** Provide your Secret Key ***"
  9. var endpoint = "https://your-endpoint"
  10.  
  11. // 创建ObsClient结构体
  12. var obsClient, _ = obs.New(ak, sk, endpoint)
  13.  
  14. func main() {
  15. input := &obs.DeleteObjectsInput{}
  16. input.Bucket = "bucketname"
  17. // 设置为verbose模式
  18. input.Quiet = false
  19. var objects [3]obs.ObjectToDelete
  20. objects[0] = obs.ObjectToDelete{Key: "key1"}
  21. objects[1] = obs.ObjectToDelete{Key: "key2"}
  22. objects[2] = obs.ObjectToDelete{Key: "key3"}
  23.  
  24. input.Objects = objects[:]
  25.  
  26. output, err := obsClient.DeleteObjects(input)
  27. if err == nil {
  28. // 获取删除成功的对象
  29. for index, deleted := range output.Deleteds {
  30. fmt.Printf("Deleted[%d]-Key:%s, VersionId:%s\n", index, deleted.Key, deleted.VersionId)
  31. }
  32. // 获取删除失败的对象
  33. for index, err := range output.Errors {
  34. fmt.Printf("Error[%d]-Key:%s, Code:%s\n", index, err.Key, err.Code)
  35. }
  36. } else if obsError, ok := err.(obs.ObsError); ok {
  37. fmt.Printf("Code:%s\n", obsError.Code)
  38. fmt.Printf("Message:%s\n", obsError.Message)
  39. }
  40. }

父主题:管理对象