bucket_cors.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package sample
  2. import (
  3. "fmt"
  4. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  5. )
  6. // BucketCORSSample 展示了如何设置/读取/清除存储空间的跨域访问(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. // 使用默认参数创建bucket
  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. // 场景1:设置Bucket的CORS规则
  33. err = client.SetBucketCORS(bucketName, []oss.CORSRule{rule1})
  34. if err != nil {
  35. HandleError(err)
  36. }
  37. // 场景2:设置Bucket的CORS规则,如果该Bucket上已经设置了CORS规则,则会覆盖。
  38. err = client.SetBucketCORS(bucketName, []oss.CORSRule{rule1, rule2})
  39. if err != nil {
  40. HandleError(err)
  41. }
  42. // 获取Bucket上设置的CORS
  43. gbl, err := client.GetBucketCORS(bucketName)
  44. if err != nil {
  45. HandleError(err)
  46. }
  47. fmt.Println("Bucket CORS:", gbl.CORSRules)
  48. // 删除Bucket上的CORS设置
  49. err = client.DeleteBucketCORS(bucketName)
  50. if err != nil {
  51. HandleError(err)
  52. }
  53. // 删除bucket
  54. err = client.DeleteBucket(bucketName)
  55. if err != nil {
  56. HandleError(err)
  57. }
  58. fmt.Println("BucketCORSSample completed")
  59. }