Tous les produits
Search
Centre de documentation

Object Storage Service:Paiement par demandeur (SDK OSS pour Go 1.0)

Dernière mise à jour :Sep 22, 2026

Lorsque l'option de paiement par demandeur est activée pour un compartiment dans Object Storage Service (OSS), le demandeur acquitte les frais de requêtes et de trafic, et non le propriétaire du compartiment. Ce dernier ne règle que les frais de stockage. Vous pouvez activer cette option pour un compartiment afin de partager les données qu'il contient sans avoir à supporter les coûts liés aux requêtes et au trafic générés par l'accès à votre compartiment.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis 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 OSS, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour savoir comment configurer ces identifiants, reportez-vous à la section Configurer les identifiants d'accès.

  • Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants issus du Security Token Service (STS), consultez Configurer un client (SDK Go V1).

  • Pour activer le paiement par demandeur, vous devez disposer de l'autorisation oss:PutBucketRequestPayment. Pour interroger la configuration de ce mode de facturation, l'autorisation oss:GetBucketRequestPayment est requise. Pour en savoir plus, consultez la page Accorder une politique personnalisée.

Activer le paiement par demandeur

Le code suivant montre comment activer le paiement par demandeur pour un compartiment :

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("New Error:", err)
		os.Exit(-1)
	}

	// Initialize the pay-by-requester mode. 
	reqPayConf := oss.RequestPaymentConfiguration{
		Payer: "Requester",
	}

	// Enable pay-by-requester for the bucket. 
	err = client.SetBucketRequestPayment("<yourBucketName>", reqPayConf)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Interroger la configuration du paiement par demandeur d'un compartiment

L'exemple de code ci-dessous permet de récupérer la configuration du paiement par demandeur associée à un compartiment :

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Query the pay-by-requester configurations of the bucket. 
	ret, err := client.GetBucketRequestPayment("yourBucketName")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Display the pay-by-requester configurations of the bucket. 
	fmt.Println("Bucket request payer:", ret.Payer)
}

Facturer les tiers lors de l'accès aux objets

Si vous décidez que les tiers doivent acquitter les frais d'accès aux objets stockés dans un compartiment, ils doivent inclure l'en-tête x-oss-request-payer:requester dans leurs requêtes HTTP pour effectuer des opérations sur vos objets. À défaut, une erreur est renvoyée.

Le code suivant illustre la facturation des tiers lors de l'accès aux objets via les opérations PutObject, GetObject et DeleteObject. Vous pouvez appliquer la même méthode pour faire supporter les coûts aux tiers lors d'opérations de lecture et d'écriture effectuées via d'autres API.

package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	payerClient, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("New Error:", err)
		os.Exit(-1)
	}

	// Specify the name of the bucket. 
	payerBucket, err := payerClient.Bucket("examplebucket")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// If pay-by-requester is enabled, external requesters must set the oss.RequestPayer(oss.Requester) parameter to access authorized content. 
	// If pay-by-requester is not enabled, external requesters are not required to include the oss.RequestPayer(oss.Requester) parameter to access the authorized content. 

	// Upload an object. 
	// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
	key := "exampledir/exampleobject.txt"
	err = payerBucket.PutObject(key, strings.NewReader("objectValue"), oss.RequestPayer("requester"))
	if err != nil {
		fmt.Println("put Error:", err)
		os.Exit(-1)
	}

	// List all objects in the bucket. 
	lor, err := payerBucket.ListObjects(oss.RequestPayer(oss.Requester))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Display the names of objects in the bucket. 
	for _, l := range lor.Objects {
		fmt.Println("the Key name is :", l.Key)
	}

	// Download the object. 
	body, err := payerBucket.GetObject(key, oss.RequestPayer(oss.Requester))
	if err != nil {
		fmt.Println("Get Error:", err)
		os.Exit(-1)
	}
	// You must close the obtained stream after the object is read. Otherwise, connection leaks may occur. Consequently, no connections are available and an exception occurs. 
	defer body.Close()

	// Read and display the obtained content. 
	data, err := io.ReadAll(body)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Println("data:", string(data))

	// Delete the object. 
	err = payerBucket.DeleteObject(key, oss.RequestPayer(oss.Requester))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Références

  • Pour consulter l'exemple de code complet relatif à la configuration du paiement par demandeur, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API permettant d'activer le paiement par demandeur, consultez PutBucketRequestPayment.

  • Pour plus d'informations sur l'opération API permettant d'interroger la configuration du paiement par demandeur, consultez GetBucketRequestPayment.