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.
Operation Required permission Configure CORS rules oss:PutBucketCorsRetrieve CORS rules oss:GetBucketCorsDelete CORS rules oss: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:
| Parameter | Type | Description |
|---|---|---|
AllowedOrigins | []string | Origins allowed to make cross-origin requests. Use * to allow any origin, or specify exact origins such as http://example.com. |
AllowedMethods | []string | HTTP methods the browser can use in cross-origin requests, for example GET, PUT, POST, DELETE, or HEAD. |
AllowedHeaders | []string | Request 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 | []string | Response 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. |
MaxAgeSeconds | int64 | How long (in seconds) the browser can cache a preflight response. Reduces the number of preflight round trips for the same resource and method. |
ResponseVary | *bool | Whether OSS includes the Vary: Origin header in responses. Set to true when your CDN or reverse proxy needs to cache responses per origin. |
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(®ion, "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)
}Verify your configuration
After calling PutBucketCors, confirm the rules are active:
Call
GetBucketCorsand check that the returnedCORSRulesmatch what you submitted.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.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
Complete sample code: put_bucket_cors.go, get_bucket_cors.go, delete_bucket_cors.go
API reference: PutBucketCors, GetBucketCors, DeleteBucketCors