Todos os produtos
Search
Central de documentação

Object Storage Service:CORS com OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Devido à política de mesma origem dos navegadores, requisições cross-origin podem ser rejeitadas durante a troca de dados ou o compartilhamento de recursos entre domínios diferentes. Este tópico descreve como resolver esses problemas configurando regras de compartilhamento de recursos de origem cruzada (CORS). Nessas regras, especifique os domínios de origem das requisições, os métodos permitidos para envio e os cabeçalhos autorizados.

Observações de uso

  • O código de exemplo deste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket ocorre via endpoint público. Para acessar esses recursos usando outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints suportados pelo OSS, consulte Regiões e endpoints do OSS.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Para configurar regras CORS, você precisa da permissão oss:PutBucketCors. Para consultar regras CORS, você precisa da permissão oss:GetBucketCors. Para excluir regras CORS, você precisa da permissão oss:DeleteBucketCors. Para obter mais informações, consulte Conceder política personalizada a usuários RAM.

Código de exemplo

Configure CORS rules

O código de exemplo a seguir mostra como configurar regras CORS para um bucket específico.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure the CORS rules for the bucket.
	request := &oss.PutBucketCorsRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		CORSConfiguration: &oss.CORSConfiguration{
			CORSRules: []oss.CORSRule{
				{
					AllowedOrigins: []string{"*"},             // Allow requests from all origins.
					AllowedMethods: []string{"PUT", "GET"},    // Allowed methods.
					AllowedHeaders: []string{"Authorization"}, // Allowed request headers.
				},
				{
					AllowedOrigins: []string{"http://example.com", "http://example.net"}, // Allow requests from specified origins.
					AllowedMethods: []string{"GET"},                                      // Allowed methods.
					AllowedHeaders: []string{"Authorization"},                            // Allowed request headers.
					ExposeHeaders:  []string{"x-oss-test", "x-oss-test1"},                // Exposed response headers.
					MaxAgeSeconds:  oss.Ptr(int64(100)),                                  // Maximum cache time. Unit: seconds.
				},
			},
			ResponseVary: oss.Ptr(false), // Whether to include the Vary header in the response.
		},
	}

	// Send the request to configure the CORS rules for the bucket.
	result, err := client.PutBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket cors %v", err)
	}

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

Query CORS rules

O código de exemplo a seguir mostra como consultar regras CORS.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the CORS configurations of the bucket.
	request := &oss.GetBucketCorsRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

	// Perform the query operation and process the result.
	getResult, err := client.GetBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket cors %v", err)
	}

	// Display the result.
	log.Printf("get bucket cors result:%#v\n", getResult.CORSConfiguration.CORSRules)
}

Delete CORS rules

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

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the CORS configurations.
	request := &oss.DeleteBucketCorsRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

	// Delete the CORS configurations and process the result.
	result, err := client.DeleteBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket cors %v", err)
	}

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

Referências