Todos os produtos
Search
Central de documentação

Object Storage Service:Configure políticas de bucket com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

As políticas de bucket concedem ou restringem o acesso de usuários anônimos ou autenticados, como contas Alibaba Cloud, usuários RAM e funções RAM, a recursos específicos do Object Storage Service (OSS). Por exemplo, você pode conceder permissões de somente leitura em recursos específicos do OSS a um usuário RAM de outra conta Alibaba Cloud.

Observações

  • Antes de configurar políticas de bucket, familiarize-se com este recurso. Para mais informações, consulte Política de Bucket.

  • O código de exemplo neste tópico usa o ID de região cn-hangzhou da região China (Hangzhou). Por padrão, o sistema usa o endpoint público. Para acessar recursos em um bucket a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints do OSS.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.

  • A permissão oss:PutBucketPolicy é necessária para configurar uma política de bucket. A permissão oss:GetBucketPolicy é necessária para consultar uma política de bucket. A permissão oss:DeleteBucketPolicy é necessária para excluir uma política de bucket. Para mais informações, consulte Autorizar políticas personalizadas para usuários RAM.

Código de exemplo

Configure uma política de bucket

O código de exemplo a seguir configura uma política de bucket.

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

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

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

	// Define the bucket policy.
	policy := `{
		"Version": "1",
		"Statement": [
			{
				"Action": [
					"oss:PutObject",
					"oss:GetObject"
				],
				"Effect": "Deny",
				"Principal": ["1234567890"],
				"Resource": ["acs:oss:*:1234567890:*/*"]
			}
		]
	}`

	// Create a request to configure a bucket policy.
	request := &oss.PutBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),       // Name of the bucket.
		Body:   strings.NewReader(policy), // The bucket policy.
	}

	// Perform the operation to configure the bucket policy.
	result, err := client.PutBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket policy %v", err)
	}

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

Consultar uma política de bucket

O código de exemplo a seguir consulta uma política de 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 // Region in which the bucket is located.
	bucketName string // 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 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")
	}

	// 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 query the bucket policy.
	request := &oss.GetBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Make the query request.
	result, err := client.GetBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket policy %v", err)
	}

	// Display the result.
	log.Printf("get bucket policy result:%#v\n", result)
}

Exclua uma política de bucket

O código de exemplo a seguir exclui uma política de 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 // Region in which the bucket is located.
	bucketName string // 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 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")
	}

	// 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 delete the bucket policy.
	request := &oss.DeleteBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Delete the bucket policy.
	result, err := client.DeleteBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket policy %v", err)
	}

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

Referências

  • Para obter o código de exemplo completo sobre como configurar uma política de bucket, visite o exemplo no GitHub.

  • Para detalhes sobre a operação de API usada para configurar uma política de bucket, consulte PutBucketPolicy.

  • O código de exemplo completo para consultar uma política de bucket está disponível no exemplo no GitHub.

  • Para informações sobre a operação de API usada para consultar uma política de bucket, veja GetBucketPolicy.

  • Acesse o exemplo no GitHub para visualizar o código de exemplo completo de exclusão de uma política de bucket.

  • Consulte DeleteBucketPolicy para conhecer a operação de API utilizada para excluir uma política de bucket.