Ao ativar o pagamento pelo solicitante em um bucket do Object Storage Service (OSS), o solicitante paga as taxas de requisições e de tráfego em vez do proprietário do bucket. O proprietário do bucket paga apenas as taxas de armazenamento. Ative o pagamento pelo solicitante em um bucket para compartilhar dados sem pagar as taxas de requisições e de tráfego geradas pelo acesso ao seu bucket.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Se precisar acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints do OSS, consulte Regions and endpoints.
Este tópico usa credenciais de acesso obtidas de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.
Este tópico mostra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para ativar o pagamento pelo solicitante, você precisa da permissão
oss:PutBucketRequestPayment. Para consultar as configurações de pagamento pelo solicitante, você precisa da permissãooss:GetBucketRequestPayment. Para obter mais informações, consulte Grant a custom policy.
Ative o pagamento pelo solicitante
O código a seguir mostra como ativar o pagamento pelo solicitante em um 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)
}
}
Consulte as configurações de pagamento pelo solicitante de um bucket
O código a seguir mostra como consultar as configurações de pagamento pelo solicitante de um 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)
}
Especifique que terceiros paguem pelo acesso a objetos
Ao especificar que terceiros paguem pelo acesso a objetos de um bucket, os solicitantes devem incluir o cabeçalho x-oss-request-payer:requester nas requisições HTTP para executar operações em seus objetos. Se esse cabeçalho não for incluído, o sistema retornará um erro.
O código a seguir mostra como especificar que terceiros paguem pelo acesso a objetos ao chamar as operações PutObject, GetObject e DeleteObject. Use esse método para definir a cobrança de terceiros em operações de leitura e gravação de objetos ao chamar outras operações da API de forma semelhante.
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)
}
}
Referências
Para obter o código de exemplo completo para configurar o pagamento pelo solicitante, visite GitHub.
Para obter mais informações sobre a operação da API usada para ativar o pagamento pelo solicitante, consulte PutBucketRequestPayment.
Para obter mais informações sobre a operação da API usada para consultar as configurações de pagamento pelo solicitante, consulte GetBucketRequestPayment.