Todos os produtos
Search
Central de documentação

Object Storage Service:Rastreamento de acesso com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como usar o OSS SDK for Go V2 para ativar o rastreamento de acesso de um bucket.

Observações de uso

  • O código de exemplo deste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, os endpoints públicos acessam os recursos do bucket. No entanto, para acessar esses recursos a partir de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regiões e endpoints do OSS.

  • Os exemplos de código leem as credenciais de acesso das variáveis de ambiente. Para saber mais sobre como configurar essas credenciais, consulte Configurar credenciais de acesso (Go SDK V1).

Código de exemplo

Enable access tracking

O código a seguir mostra como ativar o rastreamento de acesso 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"
)

// Define global variables.
var (
	region     string // The bucket region.
	bucketName string // The bucket name.
)

// The init function initializes 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.")
}

// The main function enables access tracking for 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 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 enable access tracking for the bucket.
	request := &oss.PutBucketAccessMonitorRequest{
		Bucket: oss.Ptr(bucketName),
		AccessMonitorConfiguration: &oss.AccessMonitorConfiguration{
			Status: oss.AccessMonitorStatusEnabled, // Enable access tracking.
		},
	}

	// Execute the operation to enable access tracking for the bucket.
	putResult, err := client.PutBucketAccessMonitor(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket access monitor %v", err)
	}

	// Print the result.
	log.Printf("put bucket access monitor result: %#v\n", putResult)
}

Query the access tracking status

O código a seguir mostra como consultar o status do rastreamento de acesso 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"
)

// Define global variables.
var (
	region     string // The bucket region.
	bucketName string // The bucket name.
)

// The init function initializes 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 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 query the access tracking configuration of the bucket.
	request := &oss.GetBucketAccessMonitorRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Execute the operation to query the access tracking configuration and process the result.
	result, err := client.GetBucketAccessMonitor(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket access monitor %v", err)
	}

	// Print the result.
	log.Printf("get bucket access monitor result:%#v\n", result)
}

Referências

  • Para obter mais informações sobre a operação de API que ativa o rastreamento de acesso, consulte PutBucketAccessMonitor.

  • Para obter mais informações sobre a operação de API que consulta o status do rastreamento de acesso, consulte GetBucketAccessMonitor.