All Products
Search
Document Center

Object Storage Service:CORS using OSS SDK for Go 2.0

Last Updated:Mar 19, 2026

Browsers enforce the same-origin policy, which blocks web applications from making requests to a different domain, protocol, or port. Cross-origin resource sharing (CORS) lets you define which origins, HTTP methods, and headers can access your OSS bucket — for example, to serve assets from OSS to a frontend hosted on a separate domain.

This topic covers how to configure, retrieve, and delete CORS rules using the OSS SDK for Go v2.

Prerequisites

Before you begin, ensure that you have:

  • The OSS SDK for Go v2 installed (github.com/aliyun/alibabacloud-oss-go-sdk-v2)

  • Access credentials configured as environment variables. See Configure access credentials

  • The required RAM permissions: For details on granting permissions, see Grant custom policy to RAM users.

    OperationRequired permission
    Configure CORS rulesoss:PutBucketCors
    Retrieve CORS rulesoss:GetBucketCors
    Delete CORS rulesoss:DeleteBucketCors

Usage notes

  • The sample code uses the region ID cn-hangzhou (China (Hangzhou)). By default, the public endpoint is used. To access the bucket from another Alibaba Cloud service in the same region, use the internal endpoint instead. For supported regions and endpoints, see OSS regions and endpoints.

CORS configuration parameters

All three operations share a common set of CORS rule parameters:

ParameterTypeDescription
AllowedOrigins[]stringOrigins allowed to make cross-origin requests. Use * to allow any origin, or specify exact origins such as http://example.com.
AllowedMethods[]stringHTTP methods the browser can use in cross-origin requests, for example GET, PUT, POST, DELETE, or HEAD.
AllowedHeaders[]stringRequest headers permitted in preflight requests (via Access-Control-Request-Headers). OSS returns only the headers the browser explicitly requests. Use * to allow all headers.
ExposeHeaders[]stringResponse headers that the browser can expose to client-side code, for example x-oss-test. By default, browsers expose only a limited set of headers.
MaxAgeSecondsint64How long (in seconds) the browser can cache a preflight response. Reduces the number of preflight round trips for the same resource and method.
ResponseVary*boolWhether OSS includes the Vary: Origin header in responses. Set to true when your CDN or reverse proxy needs to cache responses per origin.

Configure CORS rules

The following example uses PutBucketCorsRequest to submit a CORS configuration. The request accepts a CORSConfiguration struct containing one or more CORSRule entries.

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

var (
	region     string
	bucketName string
)

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() {
	flag.Parse()

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load credentials from environment variables and set the region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.PutBucketCorsRequest{
		Bucket: oss.Ptr(bucketName),
		CORSConfiguration: &oss.CORSConfiguration{
			CORSRules: []oss.CORSRule{
				{
					// Rule 1: allow PUT and GET from any origin.
					AllowedOrigins: []string{"*"},
					AllowedMethods: []string{"PUT", "GET"},
					AllowedHeaders: []string{"Authorization"},
				},
				{
					// Rule 2: allow GET from specific origins, expose custom headers,
					// and cache preflight responses for 100 seconds.
					AllowedOrigins: []string{"http://example.com", "http://example.net"},
					AllowedMethods: []string{"GET"},
					AllowedHeaders: []string{"Authorization"},
					ExposeHeaders:  []string{"x-oss-test", "x-oss-test1"},
					MaxAgeSeconds:  oss.Ptr(int64(100)),
				},
			},
			ResponseVary: oss.Ptr(false),
		},
	}

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

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

Retrieve CORS rules

Use GetBucketCorsRequest to retrieve the current CORS configuration. The response contains the full list of CORSRules in the CORSConfiguration field.

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

var (
	region     string
	bucketName string
)

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() {
	flag.Parse()

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.GetBucketCorsRequest{
		Bucket: oss.Ptr(bucketName),
	}

	result, err := client.GetBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket cors %v", err)
	}

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

Delete CORS rules

DeleteBucketCors removes all CORS rules from the 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"
)

var (
	region     string
	bucketName string
)

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() {
	flag.Parse()

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.DeleteBucketCorsRequest{
		Bucket: oss.Ptr(bucketName),
	}

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

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

Verify your configuration

After calling PutBucketCors, confirm the rules are active:

  1. Call GetBucketCors and check that the returned CORSRules match what you submitted.

  2. From a browser, open the Network tab in DevTools and trigger a cross-origin request to your bucket. Verify that the response includes Access-Control-Allow-Origin.

  3. If a preflight request is blocked, check:

    • The request origin is listed in AllowedOrigins (or * is set).

    • The request method is in AllowedMethods.

    • All request headers are covered by AllowedHeaders.

References