oss.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package utils
  4. import (
  5. "gd_management_gateway/common.in/config"
  6. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  7. )
  8. const (
  9. ossId = "LTAI5tAAvdM9p9h3eqRkCMW6"
  10. ossSecret = "NybirnmP0rGmkCDWkA6dEIpioShOGr"
  11. ossEndpoint = "oss-cn-hangzhou.aliyuncs.com"
  12. ossBucket = "dev-gdata-image"
  13. )
  14. func isOssConfigured() bool {
  15. if config.Conf.Oss.Endpoint == "" ||
  16. config.Conf.Oss.Bucket == "" ||
  17. config.Conf.Oss.Id == "" ||
  18. config.Conf.Oss.Secret == "" {
  19. return false
  20. }
  21. return true
  22. }
  23. // OssGetUrl 获取oss下载地址url前缀
  24. func OssGetUrl() string {
  25. if isOssConfigured() == false {
  26. return "https://" + ossBucket + "." + ossEndpoint
  27. }
  28. return "https://" + config.Conf.Oss.Bucket + "." + config.Conf.Oss.Endpoint
  29. }
  30. func ossGetInfo() (id, secret, bucket, endpoint string) {
  31. id = ossId
  32. secret = ossSecret
  33. bucket = ossBucket
  34. endpoint = ossEndpoint
  35. if isOssConfigured() {
  36. id = config.Conf.Oss.Id
  37. secret = config.Conf.Oss.Secret
  38. bucket = config.Conf.Oss.Bucket
  39. endpoint = config.Conf.Oss.Endpoint
  40. }
  41. return id, secret, bucket, endpoint
  42. }
  43. // OssUploadFile 上传文件到oss服务器
  44. func OssUploadFile(path string, fileName string) error {
  45. id, secret, buck, endpoint := ossGetInfo()
  46. client, err := oss.New(endpoint, id, secret)
  47. if err != nil {
  48. return err
  49. }
  50. // 获取存储空间。
  51. bucket, err := client.Bucket(buck)
  52. if err != nil {
  53. return err
  54. }
  55. err = bucket.PutObjectFromFile(fileName, path)
  56. return err
  57. }
  58. // OssDeleteFile 在oss服务器上删除文件
  59. func OssDeleteFile(fileName string) error {
  60. id, secret, buck, endpoint := ossGetInfo()
  61. client, err := oss.New(endpoint, id, secret)
  62. if err != nil {
  63. return err
  64. }
  65. // 获取存储空间。
  66. bucket, err := client.Bucket(buck)
  67. if err != nil {
  68. return err
  69. }
  70. err = bucket.DeleteObject(fileName)
  71. return err
  72. }