bucket_lifecycle.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package sample
  2. import (
  3. "fmt"
  4. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  5. )
  6. // BucketLifecycleSample 展示了如何设置/读取/清除存储空间中文件的生命周期(Bucket Lifecycle)
  7. func BucketLifecycleSample() {
  8. // New Client
  9. client, err := oss.New(endpoint, accessID, accessKey)
  10. if err != nil {
  11. HandleError(err)
  12. }
  13. // 使用默认参数创建bucket
  14. err = client.CreateBucket(bucketName)
  15. if err != nil {
  16. HandleError(err)
  17. }
  18. // 场景1:设置Lifecycle,其中规则的id是id1,规则生效的object前缀是one,符合的Object绝对过期时间2015/11/11
  19. var rule1 = oss.BuildLifecycleRuleByDate("id1", "one", true, 2015, 11, 11)
  20. var rules = []oss.LifecycleRule{rule1}
  21. err = client.SetBucketLifecycle(bucketName, rules)
  22. if err != nil {
  23. HandleError(err)
  24. }
  25. // 场景2:设置Lifecycle,其中规则的id是id2,规则生效的object前缀是two,符合的Object相对过期时间是3天后
  26. var rule2 = oss.BuildLifecycleRuleByDays("id2", "two", true, 3)
  27. rules = []oss.LifecycleRule{rule2}
  28. err = client.SetBucketLifecycle(bucketName, rules)
  29. if err != nil {
  30. HandleError(err)
  31. }
  32. // 场景3:在Bucket上同时设置两条规格,两个规则分别作用与不同的对象。规则id相同是会覆盖老的规则。
  33. var rule3 = oss.BuildLifecycleRuleByDays("id1", "two", true, 365)
  34. var rule4 = oss.BuildLifecycleRuleByDate("id2", "one", true, 2016, 11, 11)
  35. rules = []oss.LifecycleRule{rule3, rule4}
  36. err = client.SetBucketLifecycle(bucketName, rules)
  37. if err != nil {
  38. HandleError(err)
  39. }
  40. // 获取Bucket上设置的Lifecycle
  41. gbl, err := client.GetBucketLifecycle(bucketName)
  42. if err != nil {
  43. HandleError(err)
  44. }
  45. fmt.Println("Bucket Lifecycle:", gbl.Rules)
  46. // 删除Bucket上的Lifecycle设置
  47. err = client.DeleteBucketLifecycle(bucketName)
  48. if err != nil {
  49. HandleError(err)
  50. }
  51. // 删除bucket
  52. err = client.DeleteBucket(bucketName)
  53. if err != nil {
  54. HandleError(err)
  55. }
  56. fmt.Println("BucketLifecycleSample completed")
  57. }