Cross-origin resource sharing (CORS) allows web applications to access resources that belong to another region. OSS provides CORS APIs for convenient cross-origin access control.
For more information, see Cross-origin resource sharing and PutBucketcors in OSS Developer Guide.
For the complete code of CORS, see GitHub.
Configure CORS rules
Run the following code to configure CORS rules for the specified bucket:
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
if err ! = nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
bucketName := "<yourBucketName>"
rule1 := oss.CORSRule{
AllowedOrigin: []string{"*"},
AllowedMethod: []string{"PUT", "GET"},
AllowedHeader: []string{},
ExposeHeader: []string{},
MaxAgeSeconds: 200,
}
rule2 := oss.CORSRule{
AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
AllowedMethod: []string{"POST"},
AllowedHeader: []string{"Authorization"},
ExposeHeader: []string{"x-oss-test", "x-oss-test1"},
MaxAgeSeconds: 100,
}
// Configure CORS rules.
err = client.SetBucketCORS(bucketName, []oss.CORSRule{rule1, rule2})
if err ! = nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Obtain CORS rules
Run the following code to obtain CORS rules:
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
if err ! = nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
bucketName := "<yourBucketName>"
// Obtain the CORS ruless.
corsRes, err := client.GetBucketCORS(bucketName)
if err ! = nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("Bucket CORS:", corsRes.CORSRules)
}
Delete CORS rules
Run the following code to delete all CORS rules for the specified bucket:
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
if err ! = nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
bucketName := "<yourBucketName>"
// Delete CORS rules.
err = client.DeleteBucketCORS(bucketName)
if err ! = nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}