Todos os produtos
Search
Central de documentação

Object Storage Service:Manage bucket tagging using OSS SDK for Go 2.0

Última atualização: Sep 24, 2026

Este tópico descreve como gerenciar as tags de um bucket.

Observações de uso

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, da região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket utiliza o endpoint público. Para acessar os recursos no bucket por meio de outros produtos do Alibaba Cloud na mesma região onde o bucket está localizado, use o endpoint interno. Para obter mais informações sobre as regiões e endpoints do Object Storage Service (OSS), consulte Regions and endpoints.

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

Método

Configure as tags de um bucket

func (c *Client) PutBucketTags(ctx context.Context, request *PutBucketTagsRequest, optFns ...func(*Options)) (*PutBucketTagsResult, error)

Consulte as tags de um bucket

func (c *Client) GetBucketTags(ctx context.Context, request *GetBucketTagsRequest, optFns ...func(*Options)) (*GetBucketTagsResult, error)

Exclua as tags de um bucket

func (c *Client) DeleteBucketTags(ctx context.Context, request *DeleteBucketTagsRequest, optFns ...func(*Options)) (*DeleteBucketTagsResult, error)

Parâmetros da requisição

Parâmetro

Tipo

Descrição

ctx

context.Context

O contexto da requisição. Especifique a duração total da requisição por meio deste parâmetro.

request

*PutBucketTagsRequest

Especifique os parâmetros de uma operação de API específica. Para obter mais informações, consulte PutBucketTagsRequest.

*GetBucketTagsRequest

Especifique os parâmetros de uma operação de API específica. Para obter mais informações, consulte GetBucketTagsRequest.

*DeleteBucketTagsRequest

Especifique os parâmetros de uma operação de API específica. Para obter mais informações, consulte DeleteBucketTagsRequest.

optFns

...func(*Options)

Opcional. O parâmetro no nível da operação. Para obter mais informações, consulte Options.

Parâmetros de resposta

Parâmetro

Tipo

Descrição

result

*PutBucketTagsResult

A resposta da operação. Este parâmetro é válido quando o valor de err é nil. Para obter mais informações, consulte PutBucketTagsResult.

*GetBucketTagsRequest

A resposta da operação. Este parâmetro é válido quando o valor de err é nil. Para obter mais informações, consulte GetBucketTagsResult.

*DeleteBucketTagsRequest

A resposta da operação. Este parâmetro é válido quando o valor de err é nil. Para obter mais informações, consulte DeleteBucketTagsResult.

err

error

O status da requisição. Se a requisição falhar, o valor de err não pode ser nil.

Exemplos

Configure as tags de um bucket

O código a seguir mostra um exemplo de como configurar as tags de um bucket:

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

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

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

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 specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create a request to configure tags for the bucket.
	request := &oss.PutBucketTagsRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Tagging: &oss.Tagging{
			&oss.TagSet{
				[]oss.Tag{
					{
						Key:   oss.Ptr("k1"), // The key of a tag.
						Value: oss.Ptr("v1"), // The value of a tag.
					},
					{
						Key:   oss.Ptr("k2"), // The key of a tag.
						Value: oss.Ptr("v2"), // The value of a tag.
					},
					{
						Key:   oss.Ptr("k3"), // The key of a tag.
						Value: oss.Ptr("v3"), // The value of a tag.
					},
				},
			},
		},
	}

	// Send the request to configure tags for a bucket.
	result, err := client.PutBucketTags(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket tags %v", err)
	}

	// Display the result of the tag configuration.
	log.Printf("put bucket tags result:%#v\n", result)
}

Consulte as tags de um bucket

O código a seguir mostra um exemplo de como consultar as tags de um bucket:

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

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

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

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 specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create a request to query the tags of the bucket.
	request := &oss.GetBucketTagsRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Execute the request to query the tags of the bucket and process the result.
	getResult, err := client.GetBucketTags(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket tags %v", err)
	}

	// Display the number of bucket tags.
	log.Printf("get bucket tags result:%#v\n", len(getResult.Tagging.TagSet.Tags))
}

Exclua as tags de um bucket

Exclua uma única tag de um bucket

O código a seguir mostra um exemplo de como excluir a tag k1 de um bucket:

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

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

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

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 specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create a request to delete a tag of the bucket.
	request := &oss.DeleteBucketTagsRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Tagging: oss.Ptr("k1"),
	}

	// Execute the request to delete the tag of the bucket and process the result.
	result, err := client.DeleteBucketTags(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket tags %v", err)
	}

	// Display the result of the tag deletion.
	log.Printf("delete bucket tags result:%#v\n", result)
}

Exclua várias tags de um bucket

O código a seguir mostra um exemplo de como excluir as tags k1 e k2 de um bucket:

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

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

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

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 specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create a request to delete the two tags of the bucket.
	request := &oss.DeleteBucketTagsRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Tagging: oss.Ptr("k1,k2"),
	}

	// Execute the request to delete the tags of the bucket and process the result.
	result, err := client.DeleteBucketTags(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket tags %v", err)
	}

	// Display the result of the tag deletion.
	log.Printf("delete bucket tags result:%#v\n", result)
}

Exclua todas as tags de um bucket

O código a seguir mostra um exemplo de como excluir todas as tags de um bucket:

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

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

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

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 specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create a request to delete all tags of the bucket.
	request := &oss.DeleteBucketTagsRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Execute the request to delete all tags of the bucket and process the result.
	result, err := client.DeleteBucketTags(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket tags %v", err)
	}

	// Display the result of the tag deletion.
	log.Printf("delete bucket tags result:%#v\n", result)
}

Referências

  • Para obter mais informações sobre a operação de API usada para configurar as tags de um bucket, acesse PutBucketTags.

  • Para obter mais informações sobre a operação de API usada para consultar as tags de um bucket, acesse GetBucketTags.

  • Para obter mais informações sobre a operação de API usada para excluir as tags de um bucket, acesse DeleteBucketTags.