Todos os produtos
Search
Central de documentação

Object Storage Service:Cross-origin resource sharing (Go SDK V1)

Última atualização: Sep 22, 2026

Devido à política de mesma origem dos navegadores, estes podem rejeitar solicitações de origem cruzada durante a troca de dados ou o compartilhamento de recursos entre domínios diferentes. Para resolver esse problema, configure regras de compartilhamento de recursos de origem cruzada (CORS). Nessas regras, especifique os domínios de origem das solicitações, os métodos permitidos para enviá-las e os cabeçalhos autorizados.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Se você quiser acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico utiliza 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 demonstra 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).

  • Configurar regras CORS requer a permissão oss:PutBucketCors. Para consultá-las, é necessária a permissão oss:GetBucketCors e, para excluí-las, a permissão oss:DeleteBucketCors. Para obter mais informações, consulte Grant a custom policy.

Código de exemplo

Defina regras CORS

O código de exemplo a seguir mostra como configurar uma regra CORS para um bucket específico:

package main

import (
	"log"

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

func main() {
	// Set bucketName to the name of your bucket.
	bucketName := "yourBucketName"

	// Obtain access credentials from environment variables. Before you run this 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 {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	isTrue := true
	rule1 := oss.CORSRule{
		AllowedOrigin: []string{"*"},
		AllowedMethod: []string{"PUT", "GET", "POST"},
		AllowedHeader: []string{},
		ExposeHeader:  []string{},
		MaxAgeSeconds: 100,
	}

	rule2 := oss.CORSRule{
		AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
		AllowedMethod: []string{"GET"},
		AllowedHeader: []string{"Authorization"},
		ExposeHeader:  []string{"x-oss-test-01", "x-oss-test-02"},
		MaxAgeSeconds: 100,
	}

	put := oss.PutBucketCORS{}
	put.CORSRules = []oss.CORSRule{rule1, rule2}
	put.ResponseVary = &isTrue

	// Set the CORS rules.
	err = client.SetBucketCORSV2(bucketName, put)
	if err != nil {
		log.Fatalf("Error setting CORS rules: %v", err)
	}

	log.Println("Set Success")
}

Obtenha regras CORS

O código de exemplo a seguir mostra como consultar as regras CORS de um bucket específico:

package main

import (
	"log"

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

func main() {
	// Set bucketName to the name of your bucket.
	bucketName := "yourBucketName"

	// Obtain access credentials from environment variables. Before you run this 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 {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Get the CORS rules.
	corsRes, err := client.GetBucketCORS(bucketName)
	if err != nil {
		log.Fatalf("Error getting CORS rules: %v", err)
	}

	// Print the CORS rules.
	for _, rule := range corsRes.CORSRules {
		log.Printf("Cors Rules Allowed Origin: %v", rule.AllowedOrigin)
		log.Printf("Cors Rules Allowed Method: %v", rule.AllowedMethod)
		log.Printf("Cors Rules Allowed Header: %v", rule.AllowedHeader)
		log.Printf("Cors Rules Expose Header: %v", rule.ExposeHeader)
		log.Printf("Cors Rules Max Age Seconds: %d", rule.MaxAgeSeconds)
	}

	if corsRes.ResponseVary != nil {
		log.Printf("Cors Rules Response Vary: %t", *corsRes.ResponseVary)
	}
}

Exclua regras CORS

O código de exemplo a seguir mostra como excluir todas as regras CORS de um bucket específico:

package main

import (
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this 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 {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Set bucketName to the name of the bucket, for example, examplebucket.
	bucketName := "examplebucket"

	// Delete the CORS rules.
	err = client.DeleteBucketCORS(bucketName)
	if err != nil {
		log.Fatalf("Error deleting CORS rules: %v", err)
	}

	log.Println("Delete Bucket CORS Success")
}

Referências

  • Para acessar o código de exemplo completo de CORS, consulte o exemplo no GitHub.

  • Para obter mais informações sobre a operação de API usada para definir regras CORS, consulte SetBucketCORSV2.

  • Para detalhes sobre a operação de API de consulta de regras CORS, consulte GetBucketCORS.

  • Para mais informações sobre a operação de API de exclusão de regras CORS, consulte DeleteBucketCORS.