Todos os produtos
Search
Central de documentação

Object Storage Service:Bloqueie o acesso público a recursos do OSS no nível do ponto de acesso usando o OSS SDK for Go 2.0

Última atualização: Sep 22, 2026

Este tópico descreve como gerenciar as configurações de bloqueio de acesso público no nível do ponto de acesso usando o OSS SDK for Go V2.

Observações

  • 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 acesso aos recursos de um bucket utiliza o endpoint público. Para acessar recursos no bucket por meio de outros services da Alibaba Cloud na mesma região em que o bucket está localizado, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints compatíveis com o Object Storage Service (OSS), consulte OSS 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 credenciais de acesso, consulte Configure access credentials (Go SDK V1).

Código de exemplo

Ativar o bloqueio de acesso público para um ponto de acesso

O código a seguir apresenta um exemplo de como ativar o bloqueio de acesso público para um ponto de acesso.

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 variable to store the region information obtained from the command line.
	bucketName string // Define a variable to store the bucket name obtained from the command line.
)
 
func init() {
	// Set the command line parameter to specify the region. This parameter is left empty by default.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Set the command line parameter to specify the name of the bucket. This parameter is left empty by default.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Define the access point name, which is hardcoded as "access point name" in this example. In actual scenarios, this value should be set according to the actual business requirements or passed through command line parameters.
	var accessPointName = "access point name"

	// Check if the name of the bucket is specified. If not, the program prints an error message indicating that this parameter is required and terminates.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required") // Log the error message and terminate the program.
	}

	// Check if the region information is provided. If not, the program prints an error message indicating that this parameter is required and terminates.
	if len(region) == 0 {
		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 instance using the configurations.

	// Create a PutAccessPointPublicAccessBlock request to configure block public access settings for a specific access point.
	request := &oss.PutAccessPointPublicAccessBlockRequest{
		Bucket:          oss.Ptr(bucketName), // Specify the name of the bucket.
		AccessPointName: oss.Ptr(accessPointName), // Specify the name of the access point.
		PublicAccessBlockConfiguration: &oss.PublicAccessBlockConfiguration{
			oss.Ptr(true), // Enable block public access.
		},
	}
	putResult, err := client.PutAccessPointPublicAccessBlock(context.TODO(), request) // Send the request to configure block public access settings for the access point.
	if err != nil {
		log.Fatalf("failed to put access point public access block %v", err) // If an error occurs, record the error message and exit.
	}

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

Consultar as configurações de bloqueio de acesso público para um ponto de acesso

O exemplo abaixo demonstra como consultar as configurações de bloqueio de acesso público para um ponto de acesso.

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 variable to store the region information obtained from the command line.
	bucketName string // Define a variable to store the bucket name obtained from the command line.
)

func init() {
	// Set command line parameters to specify the region. This parameter is left empty by default.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Set command line parameters to specify the bucket name. This parameter is left empty by default.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Define the access point name, which is hardcoded as "access point name" in this example. In actual scenarios, this value should be set according to the actual business requirements or by other means.
	var accessPointName = "access point name"

	// Check if the name of the bucket is specified. If not, the program prints an error message indicating that this parameter is required and terminates.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required") // Log the error message and terminate the program.
	}

	// Check if the region information is specified. If not, the program prints an error message indicating that this parameter is required and terminates.
	if len(region) == 0 {
		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 instance using the configurations.

	// Create a GetAccessPointPublicAccessBlock request to query public access blocking configurations for the specific access point.
	request := &oss.GetAccessPointPublicAccessBlockRequest{
		Bucket:          oss.Ptr(bucketName), // Specify the name of the bucket.
		AccessPointName: oss.Ptr(accessPointName), // Specify the name of the access point.
	}
	getResult, err := client.GetAccessPointPublicAccessBlock(context.TODO(), request) // Make the query request.
	if err != nil {
		log.Fatalf("failed to get access point public access block %v", err) // If an error occurs, record the error message and terminate the program.
	}

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

Excluir as configurações de bloqueio de acesso público para um ponto de acesso

Confira a seguir um exemplo de código para excluir as configurações de bloqueio de acesso público para um ponto de acesso.

package main

import (
	"context" // Used to manage contexts 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 variable to store the region information obtained from the command line.
	bucketName string // Define a variable to store the bucket name obtained from the command line.
)

// The init function is executed before the main function to initialize the program.
func init() {
	// Set command line parameters to specify the region. This parameter is left empty by default.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Set command line parameters to specify the name of the bucket. This parameter is left empty by default.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

// The main function serves as the entry point of the program.
func main() {
	flag.Parse() // Parse command line parameters.

	// Define the access point name, which is hardcoded as "access point name" in this example. In actual scenarios, this value should be set according to the actual business requirements or by other means.
	var accessPointName = "access point name"

	// Check if the name of the bucket is specified. If not, the program prints an error message indicating that this parameter is required and terminates.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required") // Log the error message and terminate the program.
	}

	// Check if the region information is specified. If not, the program outputs default parameters and terminates.
	if len(region) == 0 {
		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 instance using the configurations.

	// Create a DeleteAccessPointPublicAccessBlock request to delete the public access blocking configurations for the specific access point.
	request := &oss.DeleteAccessPointPublicAccessBlockRequest{
		Bucket:          oss.Ptr(bucketName), // Specify the name of the bucket.
		AccessPointName: oss.Ptr(accessPointName), // Specify the name of the access point.
	}
	deleteResult, err := client.DeleteAccessPointPublicAccessBlock(context.TODO(), request) // Send the request to delete the public access blocking configurations.
	if err != nil {
		log.Fatalf("failed to delete access point public access block %v", err) // If an error occurs, record the error message and terminate the program.
	}

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

Referências

  • Para o código de exemplo completo usado para gerenciar as configurações de bloqueio de acesso público para pontos de acesso, consulte Exemplo no GitHub.

  • Para obter mais informações sobre a operação de API que você pode chamar para ativar o bloqueio de acesso público para um ponto de acesso, consulte PutAccessPointPublicAccessBlock.

  • Para obter mais informações sobre a operação de API que você pode chamar para consultar as configurações de bloqueio de acesso público para um ponto de acesso, consulte GetAccessPointPublicAccessBlock.

  • Para obter mais informações sobre a operação de API que você pode chamar para excluir as configurações de bloqueio de acesso público para um ponto de acesso, consulte DeleteAccessPointPublicAccessBlock.