utils.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package utils
  2. import (
  3. "adm-gateway/parser"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "fmt"
  7. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  8. )
  9. const (
  10. ossId = "LTAI4Fjs1bNMd8k8LT41Fxxn"
  11. ossSecret = "WlQJwVbxHIY4TIZwMIFA5QCye6n0Pl"
  12. ossEndpoint = "oss-cn-shanghai.aliyuncs.com"
  13. ossBucket = "gd-image"
  14. )
  15. func Base64Encode(src []byte) []byte {
  16. return []byte(base64.StdEncoding.EncodeToString(src))
  17. }
  18. func Base64Decode(src string) ([]byte, error) {
  19. return base64.StdEncoding.DecodeString(src)
  20. }
  21. func MD5(src string) string {
  22. h := md5.New()
  23. h.Write([]byte(src))
  24. re := h.Sum(nil)
  25. return fmt.Sprintf("%x", re)
  26. }
  27. func isOssConfigured() bool {
  28. if parser.Conf.Oss.EndPoint == "" ||
  29. parser.Conf.Oss.Bucket == "" ||
  30. parser.Conf.Oss.AccessKey == "" ||
  31. parser.Conf.Oss.AccessSecret == "" {
  32. return false
  33. }
  34. return true
  35. }
  36. // OssGetUrl 获取oss下载地址url前缀
  37. func OssGetUrl() string {
  38. if isOssConfigured() == false {
  39. return "https://" + ossBucket + "." + ossEndpoint
  40. }
  41. return "https://" + parser.Conf.Oss.Bucket + "." + parser.Conf.Oss.EndPoint
  42. }
  43. func ossGetInfo() (id, secret, bucket, endpoint string) {
  44. id = ossId
  45. secret = ossSecret
  46. bucket = ossBucket
  47. endpoint = ossEndpoint
  48. if isOssConfigured() {
  49. id = parser.Conf.Oss.AccessKey
  50. secret = parser.Conf.Oss.AccessSecret
  51. bucket = parser.Conf.Oss.Bucket
  52. endpoint = parser.Conf.Oss.EndPoint
  53. }
  54. return id, secret, bucket, endpoint
  55. }
  56. // OssUploadFile 上传文件到oss服务器
  57. func OssUploadFile(path string, fileName string) error {
  58. id, secret, buck, endpoint := ossGetInfo()
  59. client, err := oss.New(endpoint, id, secret)
  60. if err != nil {
  61. return err
  62. }
  63. // 获取存储空间。
  64. bucket, err := client.Bucket(buck)
  65. if err != nil {
  66. return err
  67. }
  68. err = bucket.PutObjectFromFile(fileName, path)
  69. return err
  70. }