Todos los productos
Search
Centro de documentos

Object Storage Service:Gestione el bloqueo de acceso público para recursos de OSS mediante OSS SDK para Go 2.0

Última actualización: Sep 03, 2026

Puede usar OSS SDK para Go V2 para habilitar el bloqueo de acceso público en recursos de Object Storage Service (OSS), así como consultar o eliminar las configuraciones de dicho bloqueo.

Notas de uso

  • El código de ejemplo usa de forma predeterminada el ID de región cn-hangzhou correspondiente a China (Hangzhou) y el endpoint público. Para acceder a los recursos mediante otros servicios de Alibaba Cloud en la misma región que el bucket, use un endpoint interno. Para obtener más información sobre las regiones y endpoints compatibles con Object Storage Service (OSS), consulte OSS regions and endpoints.

  • Las credenciales de acceso se obtienen de variables de entorno. Para más detalles sobre cómo configurar las credenciales de acceso, consulte Configure access credentials (Go SDK V1).

Código de ejemplo

Habilitar el bloqueo de acceso público

El siguiente código muestra cómo habilitar el bloqueo de acceso público para recursos de 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 las configuraciones de bloqueo de acceso público

El siguiente código muestra cómo consultar las configuraciones de bloqueo de acceso público.

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

Eliminar las configuraciones de bloqueo de acceso público

El siguiente código muestra cómo eliminar las configuraciones de bloqueo de acceso público.

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

Referencias

  • Para consultar el código de ejemplo completo, revise el ejemplo en GitHub.

  • Para la operación de API que habilita el bloqueo de acceso público, consulte PutPublicAccessBlock.

  • Para la operación de API que consulta las configuraciones de bloqueo de acceso público, consulte GetPublicAccessBlock.

  • Para la operación de API que elimina las configuraciones de bloqueo de acceso público, consulte DeletePublicAccessBlock.