Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer les configurations de blocage de l'accès public pour les buckets à l'aide du SDK OSS pour Go 2.0

Dernière mise à jour :Sep 24, 2026

Cette rubrique explique comment gérer les configurations de blocage de l'accès public pour les buckets en utilisant le SDK OSS pour Go V2.

Notes

  • L'exemple de code présenté dans cette rubrique utilise l'ID de région cn-hangzhou correspondant à la région Chine (Hangzhou). Par défaut, le point de terminaison public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez accéder aux ressources du bucket via d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison pris en charge par Object Storage Service (OSS), consultez la page Régions et points de terminaison OSS.

  • Dans cette rubrique, les identifiants d'accès sont récupérés depuis des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, reportez-vous à la section Configurer les identifiants d'accès (SDK Go V1).

Exemple de code

Activer le blocage de l'accès public pour un bucket

Le code suivant illustre la procédure pour activer le blocage de l'accès public pour un bucket.

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

// The init function is executed before the main function to initialize the program.
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 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.

	// Check if the bucket name is specified. If not, the program outputs default parameters 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 using the configurations.

	// Create a PutBucketPublicAccessBlock request to configure block public access for a bucket.
	request := &oss.PutBucketPublicAccessBlockRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
		PublicAccessBlockConfiguration: &oss.PublicAccessBlockConfiguration{
			oss.Ptr(true), // Enable block public access.
		},
	}
	putResult, err := client.PutBucketPublicAccessBlock(context.TODO(), request) // Process the request.
	if err != nil {
		log.Fatalf("failed to put bucket public access block %v", err) // If an error occurs, record the error message and terminate the program.
	}

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

Interroger les configurations de blocage de l'accès public pour un bucket

Le code suivant montre comment interroger les configurations de blocage de l'accès public pour un bucket.

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

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

	// Check if the bucket name is specified. If not, the program outputs default parameters 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 GetBucketPublicAccessBlock request to query block public access configurations.
	request := &oss.GetBucketPublicAccessBlockRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
	}
	getResult, err := client.GetBucketPublicAccessBlock(context.TODO(), request) // Process the request.
	if err != nil {
		log.Fatalf("failed to get bucket public access block %v", err) // If an error occurs, record the error message and terminate the program.
	}

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

Supprimer les configurations de blocage de l'accès public pour un bucket

Le code ci-dessous fournit un exemple de suppression des configurations de blocage de l'accès public pour un bucket.

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

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

	// Check if the bucket name is specified. If not, the program outputs default parameters 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 DeleteBucketPublicAccessBlock request to delete the block public access configurations.
	request := &oss.DeleteBucketPublicAccessBlockRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
	}
	result, err := client.DeleteBucketPublicAccessBlock(context.TODO(), request) // Process the request.
	if err != nil {
		log.Fatalf("failed to delete bucket public access block %v", err) // If an error occurs, record the error message and terminate the program.
	}

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

Références

  • Pour consulter l'exemple de code complet relatif à la gestion des configurations de blocage de l'accès public, rendez-vous sur la page Exemple Github.

  • Pour en savoir plus sur l'opération API permettant d'activer le blocage de l'accès public pour un bucket, voir PutBucketPublicAccessBlock.

  • Pour obtenir des détails sur l'opération API utilisée pour interroger les configurations de blocage de l'accès public d'un bucket, consultez GetBucketPublicAccessBlock.

  • Pour plus d'informations sur l'opération API qui permet de supprimer les configurations de blocage de l'accès public d'un bucket, reportez-vous à la documentation DeleteBucketPublicAccessBlock.