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 shows how to set, get and delete bucket's lifecycle.
  7. func BucketLifecycleSample() {
  8. // New client
  9. client, err := oss.New(endpoint, accessID, accessKey)
  10. if err != nil {
  11. HandleError(err)
  12. }
  13. // Create the bucket with default parameters
  14. err = client.CreateBucket(bucketName)
  15. if err != nil {
  16. HandleError(err)
  17. }
  18. // Case 1: Set the lifecycle. The rule ID is id1 and the applied objects' prefix is one and expired time is 11/11/2015
  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. // Case 2: Set the lifecycle, The rule ID is id2 and the applied objects' prefix is two and the expired time is three days after the object created.
  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. // Case 3: Create two rules in the bucket for different objects. The rule with the same ID will be overwritten.
  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. // Get the bucket's lifecycle
  41. gbl, err := client.GetBucketLifecycle(bucketName)
  42. if err != nil {
  43. HandleError(err)
  44. }
  45. fmt.Println("Bucket Lifecycle:", gbl.Rules)
  46. // Delete bucket's Lifecycle
  47. err = client.DeleteBucketLifecycle(bucketName)
  48. if err != nil {
  49. HandleError(err)
  50. }
  51. // Delete bucket
  52. err = client.DeleteBucket(bucketName)
  53. if err != nil {
  54. HandleError(err)
  55. }
  56. fmt.Println("BucketLifecycleSample completed")
  57. }