All Products
Search
Document Center

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

Last Updated:Aug 02, 2025

The same-origin policy in browsers prevents cross-origin requests when data is exchanged or resources are shared between different domain names. This topic describes how to resolve these cross-domain issues by setting a cross-origin access policy that allows access from specified domain names, using specified methods, and with specified request headers.

Usage notes

  • The sample code in this topic uses the China (Hangzhou) region with the ID cn-hangzhou as an example. A public endpoint is used by default. If you want to access OSS from other Alibaba Cloud products in the same region, you can use an internal endpoint. For more information about the regions and endpoints that OSS supports, see OSS regions and endpoints.

  • The examples in this topic show how to obtain access credentials from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • To set cross-origin rules, you must have the oss:PutBucketCors permission. To query cross-origin rules, you must have the oss:GetBucketCors permission. To delete cross-origin rules, you must have the oss:DeleteBucketCors permission. For more information, see Grant custom access policies to RAM users.

Sample code

Configure cross-origin resource sharing rules

You can use the following code to set the cross-origin rules for a specified bucket.

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 // The region where the bucket is located.	bucketName string // The name of the bucket. ) // The init function is 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 bucket name is empty.	if len(bucketName) == 0 {	flag.PrintDefaults()	log.Fatalf("invalid parameters, bucket name required")	}	// Check whether the region is empty.	if len(region) == 0 {	flag.PrintDefaults()	log.Fatalf("invalid parameters, region required")	}	// Load the default configurations and set 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), // The 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)), // The maximum cache time in seconds.	},	},	ResponseVary: oss.Ptr(false), // Specifies 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)	}	// Print the result of configuring the CORS rules for the bucket.	log.Printf("put bucket cors result:%#v\n", result) } 

Query cross-origin resource sharing rules

You can use the following code to query the cross-origin rules.

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 // The region where the bucket is located.	bucketName string // The name of the bucket. ) // The init function is 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 bucket name is empty.	if len(bucketName) == 0 {	flag.PrintDefaults()	log.Fatalf("invalid parameters, bucket name required")	}	// Check whether the region is empty.	if len(region) == 0 {	flag.PrintDefaults()	log.Fatalf("invalid parameters, region required")	}	// Load the default configurations and set 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 configuration of the bucket.	request := &oss.GetBucketCorsRequest{	Bucket: oss.Ptr(bucketName), // The name of the bucket.	}	// Query the CORS configuration of the bucket and process the result.	getResult, err := client.GetBucketCors(context.TODO(), request)	if err != nil {	log.Fatalf("failed to get bucket cors %v", err)	}	// Print the result of querying the CORS configuration of the bucket.	log.Printf("get bucket cors result:%#v\n", getResult.CORSConfiguration.CORSRules) } 

Delete cross-origin resource sharing rules

You can use the following code to delete all cross-origin rules of a specified bucket.

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 // The region where the bucket is located.	bucketName string // The name of the bucket. ) // The init function is 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 bucket name is empty.	if len(bucketName) == 0 {	flag.PrintDefaults()	log.Fatalf("invalid parameters, bucket name required")	}	// Check whether the region is empty.	if len(region) == 0 {	flag.PrintDefaults()	log.Fatalf("invalid parameters, region required")	}	// Load the default configurations and set 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 configuration of the bucket.	request := &oss.DeleteBucketCorsRequest{	Bucket: oss.Ptr(bucketName), // The name of the bucket.	}	// Delete the CORS configuration of the bucket and process the result.	result, err := client.DeleteBucketCors(context.TODO(), request)	if err != nil {	log.Fatalf("failed to delete bucket cors %v", err)	}	// Print the result of deleting the CORS configuration of the bucket.	log.Printf("delete bucket cors result:%#v\n", result) } 

References