Todos los productos
Search
Centro de documentos

Object Storage Service:Directivas de retención con OSS SDK for Go 2.0

Última actualización: Sep 03, 2026

Puede configurar una directiva de retención basada en tiempo para un bucket. El periodo de retención puede abarcar desde un día hasta 70 años. Este tema describe cómo crear, consultar y bloquear una directiva de retención.

Notas de uso

  • El código de ejemplo de este tema utiliza el ID de región cn-hangzhou correspondiente a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si desea usar otros servicios de Alibaba Cloud para acceder a los recursos de un bucket desde la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints que admite Object Storage Service (OSS), consulte OSS regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

Código de ejemplo

Create a retention policy

A continuación se muestra un ejemplo de código para crear una directiva de retención:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to initialize the retention policy for the bucket.
	request := &oss.InitiateBucketWormRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket for which you want to configure the retention policy.
		InitiateWormConfiguration: &oss.InitiateWormConfiguration{
			RetentionPeriodInDays: oss.Ptr(int32(30)), // Specify that the retention period of the object is 30 days.
		},
	}

	// Initialize the retention policy for the bucket and process the result.
	result, err := client.InitiateBucketWorm(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to initiate bucket worm %v", err)
	}

	// Print the result of initializing the retention policy for the bucket.
	log.Printf("initiate bucket worm result:%#v\n", result)
}

Cancel an unlocked retention policy

A continuación se muestra un ejemplo de código para cancelar una directiva de retención desbloqueada:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// Initialize command-line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Configure the OSS client.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to cancel the retention policy.
	request := &oss.AbortBucketWormRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Cancel the retention policy and process the result.
	result, err := client.AbortBucketWorm(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to abort bucket worm %v", err)
	}

	log.Printf("abort bucket worm result:%#v\n", result)
}

Lock a retention policy

A continuación se muestra un ejemplo de código para bloquear una directiva de retención:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string
	bucketName string
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	var (
		wormId = "worm id" // wormId specifies the ID of the WORM task.
	)
	// Parse command-line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client using the configurations.
	client := oss.NewClient(cfg)

	// Create a request to complete the retention policy.
	request := &oss.CompleteBucketWormRequest{
		Bucket: oss.Ptr(bucketName),
		WormId: oss.Ptr(wormId),
	}
	// Call the CompleteBucketWorm method of the client to complete the retention policy.
	result, err := client.CompleteBucketWorm(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to complete bucket worm %v", err)
	}

	log.Printf("complete bucket worm result:%#v\n", result)
}

Query a retention policy

Utilice el siguiente código para obtener la configuración de la directiva de retención:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

// The main function.
func main() {
	// Parse command-line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the retention policy configured for the bucket.
	request := &oss.GetBucketWormRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Query the retention policy configured for the bucket and process the result.
	result, err := client.GetBucketWorm(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket worm %v", err)
	}

	// Print the result of querying the retention policy configured for the bucket.
	log.Printf("get bucket worm result:%#v\n", result)
}

Extend the retention period of an object

A continuación se muestra un ejemplo de código para extender el periodo de retención de un objeto en una directiva de retención bloqueada:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	var (
		wormId = "worm id" // wormId specifies the ID of the WORM task.
	)
	// Parse command-line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to extend the retention period specified in the retention policy.
	request := &oss.ExtendBucketWormRequest{
		Bucket: oss.Ptr(bucketName),
		WormId: oss.Ptr(wormId),
		ExtendWormConfiguration: &oss.ExtendWormConfiguration{
			RetentionPeriodInDays: oss.Ptr(int32(30)), // Extend the retention period of objects in the locked retention policy to 30 days.
		},
	}

	// Extend the retention period specified in the retention policy and process the result.
	result, err := client.ExtendBucketWorm(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to extend bucket worm %v", err)
	}

	// Print the result of extending the retention period specified in the retention policy.
	log.Printf("extend bucket worm result:%#v\n", result)
}

Referencias

  • Para obtener más información sobre cómo crear una directiva de retención, consulte InitiateBucketWorm.

  • Para obtener más información sobre cómo cancelar una directiva de retención desbloqueada, consulte AbortBucketWorm.

  • Para obtener más información sobre cómo bloquear una directiva de retención, consulte CompleteBucketWorm.

  • Para obtener más información sobre cómo consultar una directiva de retención, consulte GetBucketWorm.

  • Para obtener más información sobre cómo extender el periodo de retención de un objeto, consulte ExtendBucketWorm.