Todos os produtos
Search
Central de documentação

Object Storage Service:Renomear um arquivo (Go SDK V1)

Última atualização: Jul 03, 2026

O OSS não permite renomear objetos diretamente. Para renomear um objeto, copie-o e exclua o original: chame CopyObject para criar um novo objeto com o nome desejado e, em seguida, chame DeleteObject para remover o objeto de origem.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

Código de exemplo

O código a seguir mostra como renomear o objeto srcobject.txt para destobject.txt no bucket examplebucket.

package main

import (
	"fmt"
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// The full path of the source object. The full path cannot contain the bucket name.
	srcObject := "srcobject.txt"
	// The full path of the destination object. The full path cannot contain the bucket name.
	destObject := "destobject.txt"

	// Copy srcobject.txt to destobject.txt in the same bucket.
	_, err = bucket.CopyObject(srcObject, destObject)
	if err != nil {
		log.Fatalf("Failed to copy object '%s' to '%s': %v", srcObject, destObject, err)
	}

	// Delete srcobject.txt.
	err = bucket.DeleteObject(srcObject)
	if err != nil {
		log.Fatalf("Failed to delete source object '%s': %v", srcObject, err)
	}

	fmt.Printf("%s has been renamed to %s\n", srcObject, destObject)
}

Referências

Para mais detalhes sobre as operações de API usadas para renomear um objeto, consulte CopyObject e DeleteObject.