Todos os produtos
Search
Central de documentação

Object Storage Service:Converter a classe de armazenamento de um objeto com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) oferece as seguintes classes de armazenamento para diversos cenários, desde dados quentes até frios: Standard, Infrequent Access (IA), Archive, Cold Archive e Deep Cold Archive. No OSS, após a criação de um objeto, não é possível modificar seu conteúdo. Portanto, você só pode converter a classe de armazenamento de uma cópia dele. Este tópico descreve como usar os métodos Copier.Copy ou Client.CopyObject para criar essa cópia e alterar sua classe de armazenamento.

Observações de uso

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

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Alterar a classe de armazenamento de um objeto exige as permissões oss:GetObject, oss:PutObject e oss:RestoreObject. Para obter mais informações, consulte como conceder uma política personalizada a usuários RAM.

Exemplos de código

(Recomendado) Usar o Copier para converter a classe de armazenamento

Recomendamos usar o método Copier.Copy para converter a classe de armazenamento de um objeto. Esse método integra as interfaces de cópia simples e cópia multipart e seleciona automaticamente a abordagem adequada com base nos parâmetros da solicitação.

O código a seguir exemplifica como usar o método Copier.Copy para alterar a classe de armazenamento de um objeto de Standard para Archive.

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 // Region.
	srcBucketName  string // Name of the source bucket.
	srcObjectName  string // Name of the source object.
	destBucketName string // Name of the destination bucket.
	destObjectName string // Name of the destination object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&srcBucketName, "src-bucket", "", "The name of the source bucket.")
	flag.StringVar(&srcObjectName, "src-object", "", "The name of the source object.")
	flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
	flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}

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

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

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

	// If the destination bucket name is not specified, the source bucket name is used.
	if len(destBucketName) == 0 {
		destBucketName = srcBucketName
	}

	// Check whether the source object name is specified.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, src object name required")
	}

	// Check whether the destination object name is specified.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name required")
	}

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

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

	// Create a copier.
	c := client.NewCopier()

	// Create a request to copy an object.
	request := &oss.CopyObjectRequest{
		Bucket:       oss.Ptr(destBucketName), // Name of the destination bucket.
		Key:          oss.Ptr(destObjectName), // Name of the destination object.
		SourceKey:    oss.Ptr(srcObjectName),  // Name of the source object.
		SourceBucket: oss.Ptr(srcBucketName),  // Name of the source bucket.
		StorageClass: oss.StorageClassArchive, // Specify the storage class as Archive.
	}

	// Copy the source object.
	result, err := c.Copy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to copy object %v", err) // If the copy fails, record the error message and exit.
	}

	// Display the result.
	log.Printf("copy object result:%#v\n", result)
}

Converter a classe de armazenamento usando o método CopyObject

O exemplo a seguir demonstra como usar o método CopyObject para alterar a classe de armazenamento de um objeto de Standard para Archive.

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 // Region.
	bucketName     string // Name of the source bucket.
	objectName     string // Name of the source object.
	destBucketName string // Name of the destination bucket.
	destObjectName string // Name of the destination object.
)

// Specify the init function 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 source bucket.")
	flag.StringVar(&objectName, "src-object", "", "The name of the source object.")
	flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
	flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}

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

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

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

	// If the destination bucket name is not specified, the source bucket name is used.
	if len(destBucketName) == 0 {
		destBucketName = bucketName
	}

	// Check whether the source object name is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the destination object name is specified.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name required")
	}

	// Load the default configurations and specify 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 copy an object.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:       oss.Ptr(destBucketName), // The name of the destination bucket.
		Key:          oss.Ptr(destObjectName), // The name of the destination object.
		SourceKey:    oss.Ptr(objectName),     // The name of the source object.
		SourceBucket: oss.Ptr(bucketName),     // The name of the source bucket.
		StorageClass: oss.StorageClassArchive, // Convert the storage class to Archive.
	}

	// Copy the source object and process the results.
	copyResult, err := client.CopyObject(context.TODO(), copyRequest)
	if err != nil {
		log.Fatalf("failed to copy object: %v", err)
	}
	log.Printf("copy object result: %#v\n", copyResult)
}

Referências

  • Para obter mais informações sobre a operação de API usada para converter a classe de armazenamento de objetos com o Copier, consulte Copier.Copy.

  • Para obter mais informações sobre a operação de API usada para converter a classe de armazenamento de objetos com o método CopyObject, consulte CopyObject.