edit-icon download-icon

Manage lifecycle rules

Last Updated: Nov 07, 2017

OSS allows you to set lifecycle rules for buckets to automatically remove expired objects and save the storage space. You can set multiple lifecycle rules. A lifecycle rule contains the following parts:

  • Rule ID: The ID is used for identifying the rule and cannot be repeated.
  • Prefix of objects subject to the rule: The rule is only applicable to the objects with the specified prefix.
  • Expiration time: It can be specified in either of the following ways:
    • Specifying that the object expires on the Nth day after the last modification.
    • Specifying that the object expires on a specific day. It means that all objects with the specified prefix expires after the day, regardless of the last modification time of the objects. This method is not recommended.
  • Take effect or not

For more information about the lifecycle, see Manage object lifecycle.

Note: For the example code of lifecycle management, see sample/bucket_lifecycle.go.

Set lifecycle rules

You can use Client.SetBucketLifecycle to set a lifecycle rule:

  1. import "github.com/aliyun/aliyun-oss-go-sdk/oss"
  2. client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret")
  3. if err != nil {
  4. // HandleError(err)
  5. }
  6. // id:"rule1", enable:true, prefix:"foo/", expiry:Days 3
  7. rule1 := oss.BuildLifecycleRuleByDays("rule1", "foo/", true, 3)
  8. // id:"rule2", enable:false, prefix:"bar/", expiry:Date 2016/1/1
  9. rule2 := oss.BuildLifecycleRuleByDate("rule2", "bar/", true, 2016, 1, 1)
  10. rules := []oss.LifecycleRule{rule1, rule2}
  11. err = client.SetBucketLifecycle("my-bucket", rules)
  12. if err != nil {
  13. // HandleError(err)
  14. }

View lifecycle rules

You can use Client.GetBucketLifecycle to view lifecycle rules:

  1. import "fmt"
  2. import "github.com/aliyun/aliyun-oss-go-sdk/oss"
  3. client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret")
  4. if err != nil {
  5. // HandleError(err)
  6. }
  7. lcRes, err := client.GetBucketLifecycle("my-bucket")
  8. if err != nil {
  9. // HandleError(err)
  10. }
  11. fmt.Println("Lifecycle Rules:", lcRes.Rules)

Clear lifecycle rules

You can use Client.DeleteBucketLifecycle to set a null Rule array to clear the lifecycle rules:

  1. import "github.com/aliyun/aliyun-oss-go-sdk/oss"
  2. client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret")
  3. if err != nil {
  4. // HandleError(err)
  5. }
  6. err = client.DeleteBucketLifecycle("my-bucket")
  7. if err != nil {
  8. // HandleError(err)
  9. }
Thank you! We've received your feedback.