Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar o Block Public Access para recursos do OSS com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Use o OSS SDK for Go V2 para ativar o Block Public Access em recursos do Object Storage Service (OSS), consultar ou excluir as configurações correspondentes.

Observações de uso

  • O código de exemplo usa, por padrão, o ID da região cn-hangzhou (China - Hangzhou) e o endpoint público. Para acessar recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre as regiões e os endpoints compatíveis com o Object Storage Service (OSS), consulte Regiões e endpoints do OSS.

  • As credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Go SDK V1).

Código de exemplo

Ativar o Block Public Access

O código a seguir mostra como ativar o Block Public Access para recursos do OSS.

package main

import (
	"context" 
	"flag"    
	"log"     

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"           // Import the OSS SDK package.
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" // Import the package for processing authentication information.
)

var (
	region string // Define a string variable to store the region information obtained from the command line.
)

// The init function is executed before the main function to initialize the program.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.") // Specify the region variable by parsing command-line arguments. By default, this parameter is left empty.
}

// The main function serves as the entry point for the program.
func main() {
	flag.Parse() // Parse command line parameters.
	if len(region) == 0 { // If the region parameter is not specified, the program prints an error message indicating that the region parameter is required and terminates.
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required") // Log the error message and terminate the program.
	}

	// Create a configuration object, load the credential provider from environment variables and specify the region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg) // Create a new OSS client using the configurations.

	// Create a PutPublicAccessBlock request to enable Block Public Access.
	request := &oss.PutPublicAccessBlockRequest{
		PublicAccessBlockConfiguration: &oss.PublicAccessBlockConfiguration{
			oss.Ptr(true), // Set this parameter to true to enable Block Public Access.
		},
	}
	putResult, err := client.PutPublicAccessBlock(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put public access block %v", err) // If an error occurs, record the error message and exit.
	}

	log.Printf("put public access block result:%#v\n", putResult) // Display the result.
}

Consultar as configurações de Block Public Access

O código a seguir mostra como consultar as configurações de Block Public Access.

package main

import (
	"context" // Used to manage context with features such as deadlines and cancellation signals.
	"flag"    // Used to parse command line parameters.
	"log"     // Used to print log information.

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"           // Import the OSS SDK package.
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" // Import the package for processing authentication information.
)

var (
	region string // Define a string variable to store the region information obtained from the command line.
)

// The init function used to set up tasks that are required to be completed before the program starts.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.") // Set command line parameters to specify the region, default is an empty string
}

// Entry point of the program.
func main() {
	flag.Parse() // Parse command line parameters.
	if len(region) == 0 { // If the region parameter is not provided, the program prints an error message indicating that the region parameter is required and terminates.
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required") // Log the error message and terminate the program.
	}

	// Load the default configuration, load the credential provider from environment variables and specify the region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg) // Create a new OSS client using the configurations.

	// Create a GetPublicAccessBlock request to query the Block Public Access configurations.
	request := &oss.GetPublicAccessBlockRequest{}
	getResult, err := client.GetPublicAccessBlock(context.TODO(), request) // Execute the request.
	if err != nil {
		log.Fatalf("failed to get public access block %v", err) // If an error occurs, record the error message and exit.
	}

	log.Printf("get public access block result:%#v\n", getResult) // Display the result.
}

Excluir as configurações de Block Public Access

O código a seguir mostra como excluir as configurações de Block Public Access.

package main

import (
	"context" 
	"flag"    
	"log"    

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"           // Import the OSS SDK package.
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" // Import the package for processing authentication information.
)

var (
	region string // Define a string variable to store the region information obtained from the command line.
)

// The init function is executed before the main function to initialize the program.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.") // Set command line parameters to specify the region, default is an empty string
}

// The main function serves as the entry point for the program.
func main() {
	flag.Parse() // Parse command line parameters.
	if len(region) == 0 { // If the region parameter is not provided, the program prints an error message indicating that the region parameter is required and terminates.
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required") // Log the error message and terminate the program.
	}

	// Create a configuration object, load the credential provider from environment variables and specify the region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg) // Create a new OSS client using the configuration.

	// Create a DeletePublicAccessBlock request to delete the Block Public Access configurations.
	request := &oss.DeletePublicAccessBlockRequest{}
	result, err := client.DeletePublicAccessBlock(context.TODO(), request) // Send the request.
	if err != nil {
		log.Fatalf("failed to delete public access block %v", err) // If an error occurs, record the error message and exit.
	}

	log.Printf("delete public access block result:%#v\n", result) // Display the result.
}

Referências