Todos os produtos
Search
Central de documentação

Object Storage Service:Gerencie metadados de arquivo (Go SDK V2)

Última atualização: Sep 22, 2026

Este tópico descreve como usar o oss SDK for Go para defina e obter metadados de arquivo.

Precauções

  • O código de exemplo deste tópico usa a região China (Hangzhou), cujo ID de região é cn-hangzhou. Por padrão, o SDK usa um endpoint público. Para acesse o oss a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para saber mais sobre o mapeamento entre regiões e endpoints do oss, acesse Regions and endpoints.

  • Este tópico traz exemplos de como obter credenciais de acesso por variáveis de ambiente. Para mais detalhes, configure as credenciais de acesso e acesse Configure access credentials.

  • Para defina metadados de arquivo, você precisa da permissão oss:PutObject. Para obter metadados de arquivo, você precisa da permissão oss:GetObject. Para mais informações, consulte Grant custom permissions to a RAM user.

Defina metadados ao fazer o upload de um arquivo

Defina metadados ao fazer o upload de um arquivo

O exemplo de código a seguir demonstra como defina metadados ao chamar a operação PutObject. Defina metadados como a data de expiração de um arquivo, a lista de controle de acesso (ACL) do arquivo como public-read ou metadados personalizados para identificar a finalidade ou as propriedades do arquivo. Use esse mesmo método para defina metadados em outras operações de upload. Crie um cliente oss para executar a operação.

package main

import (
	"context"
	"flag"
	"log"
	"strings"
	"time"

	"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 storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// 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.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

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

	// Define the content to upload.
	content := "hi oss"

	// 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 upload an object.
	request := &oss.PutObjectRequest{
		Bucket:  oss.Ptr(bucketName),                                                          // The bucket name.
		Key:     oss.Ptr(objectName),                                                          // The object name.
		Body:    strings.NewReader(content),                                                   // The content to upload.
		Expires: oss.Ptr(time.Date(2038, 12, 31, 12, 0, 0, 0, time.UTC).Format(time.RFC1123)), // The expiration time of the object.
		Acl:     oss.ObjectACLPublicRead,
		Metadata: map[string]string{ // Custom metadata.
			"Author": "alibaba oss sdk", // The author of the object.
			"Date":   "2024-07-01",      // The creation date of the object.
		},
	}

	// Send the request to upload the object.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Print the result of the object upload.
	log.Printf("put object result:%#v\n", result)
}

Obter metadados de arquivo

Usar o método HeadObject para obter todos os metadados de um objeto

Execute o código de exemplo a seguir para chamar o método HeadObject e obter todos os metadados de um objeto específico.

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 storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// 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.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name 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 HeadObject request.
	request := &oss.HeadObjectRequest{
		Bucket:    oss.Ptr(bucketName),      // The bucket name.
		Key:       oss.Ptr(objectName),      // The object name.
	}

	// Execute the HeadObject operation and process the result.
	result, err := client.HeadObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to head object %v", err)
	}

	// Print the result of the HeadObject operation.
	log.Printf("head object result:%#v\n", result)
}

Usar o método GetObjectMeta para obter metadados parciais de um objeto

Nota

Chame o método GetObjectMeta para obter apenas um subconjunto dos metadados de um objeto, como o tamanho do conteúdo (ContentLength), ETag, data e hora da última modificação (LastModified), data e hora do último acesso (LastAccessTime), ID da versão (VersionId) e o valor CRC de 64 bits (HashCRC64) do objeto.

Execute o exemplo de código a seguir para chamar o método GetObjectMeta e obter metadados parciais de um objeto específico.

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 storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// 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.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name 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 obtain the object metadata.
	request := &oss.GetObjectMetaRequest{
		Bucket:    oss.Ptr(bucketName),      // The bucket name.
		Key:       oss.Ptr(objectName),      // The object name.
	}

	// Execute the operation to obtain the object metadata and process the result.
	result, err := client.GetObjectMeta(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get object meta %v", err)
	}

	// Print the result of obtaining the object metadata.
	log.Printf("get object meta result:%#v\n", result)
}

Modifique os metadados de um arquivo existente

Usar o método **CopyObject** para modifique metadados de objeto

O exemplo de código a seguir demonstra como chamar o método CopyObject para defina os metadados do objeto de destino durante a operação de cópia. Especifique os metadados do objeto de destino.

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 storage region.
	srcBucketName  string // The source bucket name.
	srcObjectName  string // The source object name.
	destBucketName string // The destination bucket name.
	destObjectName string // The destination object name.
)

// 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(&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 empty.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source bucket name required")
	}

	// Check whether the region is empty.
	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 empty.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the destination object name is empty.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name 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 metadata.
	metaData := map[string]string{
		"x-oss-meta-tag1": "value1", // The metadata key is x-oss-meta-tag1, and the value is value1.
		"x-oss-meta-tag2": "value2", // The metadata key is x-oss-meta-tag2, and the value is value2.
	}

	// Create a request to copy the object.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:            oss.Ptr(destBucketName), // The destination bucket name.
		Key:               oss.Ptr(destObjectName), // The destination object name.
		SourceKey:         oss.Ptr(srcObjectName),  // The source object name.
		SourceBucket:      oss.Ptr(srcBucketName),  // The source bucket name.
		Metadata:          metaData,                // Specify the metadata of the destination object.
		MetadataDirective: oss.Ptr("Replace"),      // Do not copy the metadata of the source object.
	}

	// Execute the copy object operation and process the result.
	copyResult, err := client.CopyObject(context.TODO(), copyRequest)
	if err != nil {
		log.Fatalf("failed to copy object: %v", err)
	}

	log.Printf("copy object result versionId:%#v\n", copyResult)

}

Usar o método **Copier.Copy** do gerenciador de cópia para modifique metadados de objeto

O exemplo de código a seguir demonstra como chamar o método Copier.Copy do gerenciador de cópia para defina os metadados do objeto de destino ao copiar o objeto source. Substitua os metadados originais, limpe-os ou atualize partes deles. Após concluir a operação de cópia, escolha se deseja exclua o objeto source.

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 storage region.
	srcBucketName  string // The source bucket name.
	srcObjectName  string // The source object name.
	destBucketName string // The destination bucket name.
	destObjectName string // The destination object name.
)

// 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(&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 empty.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the storage region is empty.
	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 empty.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, src object name required")
	}

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

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

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

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

	// Set the metadata of the destination object.
	metaData := map[string]string{
		"x-oss-meta-tag1": "value1",
		"x-oss-meta-tag2": "value2",
	}
	// Build a request to copy the object.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:       oss.Ptr(destBucketName), // The destination bucket name.
		Key:          oss.Ptr(destObjectName), // The destination object name.
		SourceKey:    oss.Ptr(srcObjectName),  // The source object name.
		SourceBucket: oss.Ptr(srcBucketName),  // The source bucket name.
		Metadata:     metaData,                // Specify the metadata of the destination object.
		MetadataDirective: oss.Ptr("Replace"),  // Do not copy the metadata of the source object.
	}

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

	// Build a request to delete the object.
	deleteRequest := &oss.DeleteObjectRequest{
		Bucket: oss.Ptr(srcBucketName), // The bucket name.
		Key:    oss.Ptr(srcObjectName), // The name of the object to delete.
	}

	// Execute the delete object operation.
	deleteResult, err := client.DeleteObject(context.TODO(), deleteRequest)
	if err != nil {
		log.Fatalf("failed to delete multiple objects %v", err)
	}

	// Print the result of the copy object operation.
	log.Printf("copy object result:%#v\n", result)
	// Print the result of the delete object operation.
	log.Printf("delete objects result:%#v\n", deleteResult)
}

Referências

  • Para mais detalhes sobre a operação de API usada para defina metadados de arquivo, consulte PutObject.

  • Para saber mais sobre a operação de API usada para obter metadados de arquivo, consulte GetObject.