sign_url.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package sample
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "strings"
  7. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  8. )
  9. // SignURLSample signs URL sample
  10. func SignURLSample() {
  11. // Create bucket
  12. bucket, err := GetTestBucket(bucketName)
  13. if err != nil {
  14. HandleError(err)
  15. }
  16. // Put object
  17. signedURL, err := bucket.SignURL(objectKey, oss.HTTPPut, 60)
  18. if err != nil {
  19. HandleError(err)
  20. }
  21. var val = "花间一壶酒,独酌无相亲。 举杯邀明月,对影成三人。"
  22. err = bucket.PutObjectWithURL(signedURL, strings.NewReader(val))
  23. if err != nil {
  24. HandleError(err)
  25. }
  26. // Put object with option
  27. options := []oss.Option{
  28. oss.Meta("myprop", "mypropval"),
  29. oss.ContentType("image/tiff"),
  30. }
  31. signedURL, err = bucket.SignURL(objectKey, oss.HTTPPut, 60, options...)
  32. if err != nil {
  33. HandleError(err)
  34. }
  35. err = bucket.PutObjectFromFileWithURL(signedURL, localFile, options...)
  36. if err != nil {
  37. HandleError(err)
  38. }
  39. // Get object
  40. signedURL, err = bucket.SignURL(objectKey, oss.HTTPGet, 60)
  41. if err != nil {
  42. HandleError(err)
  43. }
  44. body, err := bucket.GetObjectWithURL(signedURL)
  45. if err != nil {
  46. HandleError(err)
  47. }
  48. defer body.Close()
  49. // Read content
  50. data, err := ioutil.ReadAll(body)
  51. if err != nil {
  52. fmt.Println("Error:", err)
  53. os.Exit(-1)
  54. }
  55. fmt.Println("data:", string(data))
  56. err = bucket.GetObjectToFileWithURL(signedURL, "mynewfile-1.jpg")
  57. if err != nil {
  58. HandleError(err)
  59. }
  60. // Delete the object and bucket
  61. err = DeleteTestBucketAndObject(bucketName)
  62. if err != nil {
  63. HandleError(err)
  64. }
  65. fmt.Println("SignURLSample completed")
  66. }