cname_sample.go 1.9 KB

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