bucket_cors.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package sample
  2. import (
  3. "fmt"
  4. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  5. )
  6. // BucketCORSSample shows how to get or set the bucket CORS.
  7. func BucketCORSSample() {
  8. // New client
  9. client, err := oss.New(endpoint, accessID, accessKey)
  10. if err != nil {
  11. HandleError(err)
  12. }
  13. // Create the bucket with default parameters
  14. err = client.CreateBucket(bucketName)
  15. if err != nil {
  16. HandleError(err)
  17. }
  18. rule1 := oss.CORSRule{
  19. AllowedOrigin: []string{"*"},
  20. AllowedMethod: []string{"PUT", "GET", "POST"},
  21. AllowedHeader: []string{},
  22. ExposeHeader: []string{},
  23. MaxAgeSeconds: 100,
  24. }
  25. rule2 := oss.CORSRule{
  26. AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
  27. AllowedMethod: []string{"GET"},
  28. AllowedHeader: []string{"Authorization"},
  29. ExposeHeader: []string{"x-oss-test", "x-oss-test1"},
  30. MaxAgeSeconds: 100,
  31. }
  32. // Case 1: Set the bucket CORS rules
  33. err = client.SetBucketCORS(bucketName, []oss.CORSRule{rule1})
  34. if err != nil {
  35. HandleError(err)
  36. }
  37. // Case 2: Set the bucket CORS rules. if CORS rules exist, they will be overwritten.
  38. err = client.SetBucketCORS(bucketName, []oss.CORSRule{rule1, rule2})
  39. if err != nil {
  40. HandleError(err)
  41. }
  42. // Get the bucket's CORS
  43. gbl, err := client.GetBucketCORS(bucketName)
  44. if err != nil {
  45. HandleError(err)
  46. }
  47. fmt.Println("Bucket CORS:", gbl.CORSRules)
  48. // Delete bucket's CORS
  49. err = client.DeleteBucketCORS(bucketName)
  50. if err != nil {
  51. HandleError(err)
  52. }
  53. // Delete bucket
  54. err = client.DeleteBucket(bucketName)
  55. if err != nil {
  56. HandleError(err)
  57. }
  58. fmt.Println("BucketCORSSample completed")
  59. }