cname_sample.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package sample
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "strings"
  6. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  7. )
  8. // CnameSample shows the cname usage
  9. func CnameSample() {
  10. // New client
  11. client, err := oss.New(endpoint4Cname, accessID, accessKey, oss.UseCname(true))
  12. if err != nil {
  13. HandleError(err)
  14. }
  15. // Create bucket
  16. err = client.CreateBucket(bucketName)
  17. if err != nil {
  18. HandleError(err)
  19. }
  20. // Set bucket ACL
  21. err = client.SetBucketACL(bucketName, oss.ACLPrivate)
  22. if err != nil {
  23. HandleError(err)
  24. }
  25. // Look up bucket ACL
  26. gbar, err := client.GetBucketACL(bucketName)
  27. if err != nil {
  28. HandleError(err)
  29. }
  30. fmt.Println("Bucket ACL:", gbar.ACL)
  31. // List buckets, the list operation could not be done by cname's endpoint
  32. _, err = client.ListBuckets()
  33. if err == nil {
  34. HandleError(err)
  35. }
  36. bucket, err := client.Bucket(bucketName)
  37. if err != nil {
  38. HandleError(err)
  39. }
  40. objectValue := "长忆观潮, 满郭人争江上望。来疑沧海尽成空, 万面鼓声中。弄潮儿向涛头立, 手把红旗旗不湿。别来几向梦中看, 梦觉尚心寒。"
  41. // Put object
  42. err = bucket.PutObject(objectKey, strings.NewReader(objectValue))
  43. if err != nil {
  44. HandleError(err)
  45. }
  46. // Get object
  47. body, err := bucket.GetObject(objectKey)
  48. if err != nil {
  49. HandleError(err)
  50. }
  51. data, err := ioutil.ReadAll(body)
  52. body.Close()
  53. if err != nil {
  54. HandleError(err)
  55. }
  56. fmt.Println(objectKey, ":", string(data))
  57. // Put object from file
  58. err = bucket.PutObjectFromFile(objectKey, localFile)
  59. if err != nil {
  60. HandleError(err)
  61. }
  62. // Get object to file
  63. err = bucket.GetObjectToFile(objectKey, localFile)
  64. if err != nil {
  65. HandleError(err)
  66. }
  67. // List objects
  68. lor, err := bucket.ListObjects()
  69. if err != nil {
  70. HandleError(err)
  71. }
  72. fmt.Println("objects:", lor.Objects)
  73. // Delete object
  74. err = bucket.DeleteObject(objectKey)
  75. if err != nil {
  76. HandleError(err)
  77. }
  78. fmt.Println("CnameSample completed")
  79. }