Todos os produtos
Search
Central de documentação

Object Storage Service:Políticas de retenção com o OSS SDK for Go 2.0

Última atualização: Sep 22, 2026

É possível configurar uma política de retenção baseada em tempo para um bucket. O período de retenção pode variar de um dia a 70 anos. Este tópico descreve como criar, consultar e bloquear uma política de retenção.

Notas de uso

  • O código de exemplo deste tópico usa o ID da região cn-hangzhou, que corresponde à região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket utiliza um endpoint público. Para acessar os recursos de um bucket na mesma região por meio de outros serviços da Alibaba Cloud, use um endpoint interno. Para mais informações sobre as regiões e os endpoints compatíveis com o Object Storage Service (OSS), consulte OSS regions and endpoints.

  • Neste tópico, o código obtém as credenciais de acesso a partir de variáveis de ambiente. Para mais detalhes sobre como configurar essas credenciais, consulte Configure access credentials.

Código de exemplo

Crie uma política de retenção

O código a seguir mostra como criar uma política de retenção:

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)
}

Cancele uma política de retenção desbloqueada

O código a seguir mostra como cancelar uma política de retenção 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)
}

Bloqueie uma política de retenção

O código a seguir mostra como bloquear uma política de retenção:

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)
}

Consulte uma política de retenção

Use o código a seguir para obter a configuração da política de retenção:

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)
}

Estenda o período de retenção de um objeto

O código a seguir mostra como estender o período de retenção de um objeto em uma política de retenção 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)
}

Referências

  • Para mais detalhes sobre a criação de uma política de retenção, consulte InitiateBucketWorm.

  • Para cancelar uma política de retenção desbloqueada, veja AbortBucketWorm.

  • Para entender o processo de bloqueio de uma política de retenção, consulte CompleteBucketWorm.

  • Para mais informações sobre a consulta de uma política de retenção, acesse GetBucketWorm.

  • Para saber como estender o período de retenção de um objeto, consulte ExtendBucketWorm.