edit-icon download-icon

CORS

Last Updated: Nov 07, 2017

Cross-origin Resource Sharing (CORS) allows web applications to access resources in other domains. The OSS provides an interface for developers to conveniently control cross-origin access permissions. For more information about CORS, see Cross-origin resource sharing.

OSS CORS settings contain one or more CORS rules. Each CORS rule includes the following parameters:

  • allowed_origins: The origins allowed for cross-origin requests, for example, www.my-domain.com, *
  • allowed_methods: The HTTP methods (PUT/POST/GET/DELETE/HEAD) allowed for cross-origin requests
  • allowed_headers: The headers allowed in a prefetch command (OPTIONS), for example, x-oss-test, *
  • expose_headers: The headers allowed for the user to access in the application
  • max_age_seconds: The cache time for the returned result of a browser prefetch (OPTIONS) request to a specific resource

Note: For the example code of CORS, see sample/bucket_cors.go.

Configure CORS rules

You can use Client.SetBucketCORS to configure CORS rules:

  1. import "github.com/aliyun/aliyun-oss-go-sdk/oss"
  2. client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret")
  3. if err != nil {
  4. // HandleError(err)
  5. }
  6. rule1 := oss.CORSRule{
  7. AllowedOrigin: []string{"*"},
  8. AllowedMethod: []string{"PUT", "GET"},
  9. AllowedHeader: []string{},
  10. ExposeHeader: []string{},
  11. MaxAgeSeconds: 200,
  12. }
  13. rule2 := oss.CORSRule{
  14. AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
  15. AllowedMethod: []string{"POST"},
  16. AllowedHeader: []string{"Authorization"},
  17. ExposeHeader: []string{"x-oss-test", "x-oss-test1"},
  18. MaxAgeSeconds: 100,
  19. }
  20. err = client.SetBucketCORS("my-bucket", []oss.CORSRule{rule1, rule2})
  21. if err != nil {
  22. // HandleError(err)
  23. }

View CORS rules

You can use Client.GetBucketCORS to view CORS rules:

  1. import "fmt"
  2. import "github.com/aliyun/aliyun-oss-go-sdk/oss"
  3. client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret")
  4. if err != nil {
  5. // HandleError(err)
  6. }
  7. corsRes, err := client.GetBucketCORS("my-bucket")
  8. if err != nil {
  9. // HandleError(err)
  10. }
  11. fmt.Println("Bucket CORS:", corsRes.CORSRules)

Clear CORS rules

You can use Client.DeleteBucketCORS to clear CORS rules:

  1. import "github.com/aliyun/aliyun-oss-go-sdk/oss"
  2. client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret")
  3. if err != nil {
  4. // HandleError(err)
  5. }
  6. err = client.DeleteBucketCORS("my-bucket")
  7. if err != nil {
  8. // HandleError(err)
  9. }
Thank you! We've received your feedback.