Todos os produtos
Search
Central de documentação

Object Storage Service:Adicionar tags a objetos com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) permite adicionar tags a objetos para classificação. Este tópico descreve como adicionar tags com o OSS SDK for Go V2.

Observações

  • Os códigos de exemplo deste tópico usam o ID da região cn-hangzhou, referente à região China (Hangzhou). Por padrão, o acesso aos recursos em um bucket ocorre via endpoint público. Para acessar os recursos do bucket por meio de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para 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 saber mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • A permissão oss:PutObjectTagging é necessária para aplicar tags em objetos. Para mais detalhes, consulte Conceder permissões personalizadas a usuários RAM.

Adicionar tags durante o upload de um objeto

Add tags to an object in an simple upload task

O código a seguir demonstra como adicionar tags ao fazer o upload do objeto.

package main

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

	"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 in which the bucket is located.
	bucketName string // Name of the bucket.
	objectName string // Name of the 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 bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 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")
	}

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

	// Specify the content that you want to upload.
	content := "hi oss"

	// 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 upload the object.
	request := &oss.PutObjectRequest{
		Bucket:  oss.Ptr(bucketName),                // Name of the bucket.
		Key:     oss.Ptr(objectName),                // Name of the object.
		Body:    strings.NewReader(content),         // Content to upload.
		Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

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

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

Add tags to an object when you perform multipart upload

O exemplo a seguir ilustra como incluir tags durante um upload multipart.

package main

import (
	"bufio"
	"bytes"
	"context"
	"flag"
	"io"
	"log"
	"os"
	"sync"

	"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 in which the bucket is located.
	bucketName string // Name of the source bucket.
	objectName string // Name of the source 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, "object", "", "The name of the source object.")
}

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

	// Specify the upload ID.
	var uploadId string

	// Check whether the name of the source bucket 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")
	}

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

	// Initialize the multipart upload request.
	initRequest := &oss.InitiateMultipartUploadRequest{
		Bucket:  oss.Ptr(bucketName),
		Key:     oss.Ptr(objectName),
		Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

	// Execute the request to initiate the multipart upload task.
	initResult, err := client.InitiateMultipartUpload(context.TODO(), initRequest)
	if err != nil {
		log.Fatalf("failed to initiate multipart upload %v", err)
	}

	// Display the result of initialisation.
	log.Printf("initiate multipart upload result:%#v\n", *initResult.UploadId)
	uploadId = *initResult.UploadId

	// Initialize the wait group and mutex.
	var wg sync.WaitGroup
	var parts []oss.UploadPart
	count := 3
	var mu sync.Mutex

	// Read data from the local file to the memory and replace yourLocalFile with the actual path of the local file that contains the file name.
	file, err := os.Open("/Users/leyinhui/Downloads/iTerm2")
	if err != nil {
		log.Fatalf("failed to open local file %v", err)
	}
	defer file.Close()

	bufReader := bufio.NewReader(file)
	content, err := io.ReadAll(bufReader)
	if err != nil {
		log.Fatalf("failed to read local file %v", err)
	}
	log.Printf("file size: %d\n", len(content))

	// Calculate the size of each part.
	chunkSize := len(content) / count
	if chunkSize == 0 {
		chunkSize = 1
	}

	// Start multiple goroutines for the multipart upload task.
	for i := 0; i < count; i++ {
		start := i * chunkSize
		end := start + chunkSize
		if i == count-1 {
			end = len(content)
		}

		wg.Add(1)
		go func(partNumber int, start, end int) {
			defer wg.Done()

			// Create the multipart upload request.
			partRequest := &oss.UploadPartRequest{
				Bucket:     oss.Ptr(bucketName),                 // Name of the destination bucket.
				Key:        oss.Ptr(objectName),                 // Name of the destination object.
				PartNumber: int32(partNumber),                   // Number of the part.
				UploadId:   oss.Ptr(uploadId),                   // Upload ID.
				Body:       bytes.NewReader(content[start:end]), // Content of the part.
			}

			// Send the request to upload the part.
			partResult, err := client.UploadPart(context.TODO(), partRequest)
			if err != nil {
				log.Fatalf("failed to upload part %d: %v", partNumber, err)
			}

			// Display the result of the request.
			part := oss.UploadPart{
				PartNumber: partRequest.PartNumber,
				ETag:       partResult.ETag,
			}

			// Use the mutex to protect shared data.
			mu.Lock()
			parts = append(parts, part)
			mu.Unlock()
		}(i+1, start, end)
	}

	// Wait until all goroutines are complete.
	wg.Wait()

	// Complete the multipart upload task.
	request := &oss.CompleteMultipartUploadRequest{
		Bucket:   oss.Ptr(bucketName),
		Key:      oss.Ptr(objectName),
		UploadId: oss.Ptr(uploadId),
		CompleteMultipartUpload: &oss.CompleteMultipartUpload{
			Parts: parts,
		},
	}
	result, err := client.CompleteMultipartUpload(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to complete multipart upload %v", err)
	}

	// Display the results.
	log.Printf("complete multipart upload result:%#v\n", result)
}

Add tags to an object when you perform append upload

O código a seguir mostra como definir tags em uma operação de append upload.

package main

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

	"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
	objectName string
)

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

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

	// Specify the position from which the append operation starts.
	var (
		position = int64(0)
	)

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 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")
	}

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, 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)

	// Specify the content that you want to append.
	content := "hi append object"

	// Create an AppendObject request to perform the first append operation.
	request := &oss.AppendObjectRequest{
		Bucket:   oss.Ptr(bucketName),
		Key:      oss.Ptr(objectName),
		Position: oss.Ptr(position),
		Body:     strings.NewReader(content),
		Tagging:  oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

	// Perform the first append operation and process the results.
	// The first time an object is appended, the append operation starts at 0. The position for the next append operation is included in the response.
	result, err := client.AppendObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to append object %v", err)
	}

	// Create an AppendObject request to perform the second append operation.
	request = &oss.AppendObjectRequest{
		Bucket:   oss.Ptr(bucketName),
		Key:      oss.Ptr(objectName),
		Position: oss.Ptr(result.NextPosition), // Obtain NextPosition from the return value of the first AppendObject
		Body:     strings.NewReader("hi append object"),
	}

	// Perform the second append operation and process the results.
	result, err = client.AppendObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to append object %v", err)
	}

	log.Printf("append object result:%#v\n", result)
}

Add tags to an object when you copy the object

O trecho de código a seguir exemplifica a adição de tags durante a cópia de um objeto.

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 in which the bucket is located.
	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 name of the source bucket is specified.
	if len(srcBucketName) == 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 = srcBucketName
	}

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

	// Check whether the name of the destination object 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 the object.
	copyRequest := &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.StorageClassStandard,           // Set the storage class to Standard.
		TaggingDirective: oss.Ptr("Replace"),                 // Ignore the tags of the source object.
		Tagging:          oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

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

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

}

Adicionar ou modificar tags de objetos existentes

Add tags to or modify the tags of existing objects

Se um objeto existente não tiver tags ou se as tags atuais não atenderem às suas necessidades, adicione ou modifique as tags do objeto.

O código a seguir mostra como adicionar ou alterar tags em um objeto já armazenado.

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 in which the bucket is located.
	bucketName string // Name of the bucket.
	objectName string // Name of the 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 bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

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

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

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, 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 add tags.
	putRequest := &oss.PutObjectTaggingRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		Key:    oss.Ptr(objectName), // Name of the object.
		Tagging: &oss.Tagging{
			TagSet: &oss.TagSet{
				Tags: []oss.Tag{
					{
						Key:   oss.Ptr("k1"), // Tag key.
						Value: oss.Ptr("v1"), // Tag value.
					},
					{
						Key:   oss.Ptr("k2"), // Tag key.
						Value: oss.Ptr("v2"), // Tag value.
					},
				},
			},
		},
	}

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

	// Display the results.
	log.Printf("put object tagging result:%#v\n", putResult)
}

Referências

  • Para obter o código de exemplo completo sobre configuração de tags em objetos, visite o GitHub.

  • Para obter mais detalhes sobre a operação de API usada na configuração de tags de objetos, consulte PutObjectTagging.