Todos los productos
Search
Centro de documentos

Object Storage Service:Pago por solicitante (OSS SDK for Go 1.0)

Última actualización: Sep 03, 2026

Cuando se habilita el pago por solicitante para un bucket en Object Storage Service (OSS), los cargos por solicitudes y tráfico se facturan al solicitante en lugar del propietario del bucket. El propietario del bucket solo paga las tarifas de almacenamiento. Puede habilitar el pago por solicitante en un bucket para compartir datos sin asumir los costos de solicitud y tráfico generados por el acceso a su bucket.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para habilitar el pago por solicitante, debe contar con el permiso oss:PutBucketRequestPayment. Para consultar las configuraciones de pago por solicitante, debe tener el permiso oss:GetBucketRequestPayment. Para obtener más información, consulte Grant a custom policy.

Habilitar el pago por solicitante

A continuación se muestra un ejemplo de código para habilitar el pago por solicitante en un bucket:

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

Consultar las configuraciones de pago por solicitante de un bucket

A continuación se muestra un ejemplo de código para consultar las configuraciones de pago por solicitante de un bucket:

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

Especificar que terceros asuman los cargos al acceder a objetos

Si especifica que los terceros deben pagar por el acceso a los objetos de un bucket, los solicitantes deben incluir el encabezado x-oss-request-payer:requester en las solicitudes HTTP para realizar operaciones en sus objetos. Si no se incluye este encabezado, se devuelve un error.

El siguiente código ejemplifica cómo especificar que terceros asuman los cargos al acceder a objetos mediante las operaciones PutObject, GetObject y DeleteObject. Puede utilizar este mismo método para indicar que terceros paguen por operaciones de lectura y escritura en objetos al invocar otras operaciones de API de manera similar.

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

Referencias

  • Para consultar el código de ejemplo completo sobre la configuración del pago por solicitante, visite GitHub.

  • Para obtener más información sobre la operación de API que permite habilitar el pago por solicitante, consulte PutBucketRequestPayment.

  • Para obtener más información sobre la operación de API que permite consultar las configuraciones de pago por solicitante, consulte GetBucketRequestPayment.