Todos os produtos
Search
Central de documentação

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

Última atualização: Jul 03, 2026

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

Observações de uso

  • 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 do bucket ocorre pelo endpoint público. Para acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, use o endpoint interno. Para mais informações sobre regiões e endpoints do Object Storage Service (OSS), consulte Regiões e endpoints.

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

Método

Configurar tags para um bucket

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

Consultar as tags de um bucket

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

Excluir as tags de um bucket

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

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

ctx

context.Context

Contexto da solicitação. Use este parâmetro para especificar a duração total da requisição.

request

*PutBucketTagsRequest

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

*GetBucketTagsRequest

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

*DeleteBucketTagsRequest

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

optFns

...func(*Options)

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

Parâmetros de resposta

Parâmetro

Tipo

Descrição

result

*PutBucketTagsResult

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

*GetBucketTagsRequest

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

*DeleteBucketTagsRequest

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

err

error

Status da solicitação. Se a requisição falhar, o valor de err não será nil.

Exemplos

Configurar tags para um bucket

O código a seguir mostra como configurar tags para 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)
}

Consultar as tags de um bucket

O código a seguir mostra 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))
}

Excluir as tags de um bucket

Excluir uma única tag de um bucket

O código a seguir mostra 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)
}

Excluir várias tags de um bucket

O código a seguir mostra 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)
}

Excluir todas as tags de um bucket

O código a seguir mostra 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 detalhes sobre a operação da API usada para configurar tags em um bucket, consulte PutBucketTags.

  • Para obter detalhes sobre a operação da API usada para consultar as tags de um bucket, consulte GetBucketTags.

  • Para obter detalhes sobre a operação da API usada para excluir as tags de um bucket, consulte DeleteBucketTags.