minio.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package oss
  2. import (
  3. "context"
  4. "errors"
  5. "eta/eta_email_analysis/global"
  6. "fmt"
  7. "github.com/minio/minio-go/v7"
  8. "github.com/minio/minio-go/v7/pkg/credentials"
  9. "log"
  10. "time"
  11. )
  12. type MinioOss struct{}
  13. // UploadFile 上传文件
  14. func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
  15. if global.CONFIG.Oss.AccessKeyId == `` || global.CONFIG.Oss.AccessKeySecret == `` {
  16. return "0", errors.New("MinIo信息未配置")
  17. }
  18. ctx := context.Background()
  19. // 此处兼容一下前后端endpoint不一致的情况, 前端用minio_endpoint后端用minio_back_endpoint, minio_back_endpoint为空则都取前者
  20. endpoint := global.CONFIG.Oss.EndPoint
  21. if global.CONFIG.Oss.BackEndPoint != "" {
  22. endpoint = global.CONFIG.Oss.BackEndPoint
  23. }
  24. accessKeyID := global.CONFIG.Oss.AccessKeyId
  25. secretAccessKey := global.CONFIG.Oss.AccessKeySecret
  26. useSSL := false
  27. if !global.CONFIG.Oss.DisableSSL {
  28. useSSL = true
  29. }
  30. minioClient, err := minio.New(endpoint, &minio.Options{
  31. Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
  32. Secure: useSSL,
  33. })
  34. if err != nil {
  35. log.Fatalln(err)
  36. return "1", err
  37. }
  38. bucketName := global.CONFIG.Oss.BucketName
  39. exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
  40. if errBucketExists != nil || !exists {
  41. err = fmt.Errorf("BucketExists: %v; err: %v", exists, errBucketExists)
  42. return "2", err
  43. }
  44. path := savePath
  45. if savePath == "" {
  46. path = global.CONFIG.Oss.UploadDir + time.Now().Format("200601/20060102/") + fileName
  47. }
  48. _, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
  49. if err != nil {
  50. log.Fatalln(err)
  51. return "3", err
  52. }
  53. resourceUrl := global.CONFIG.Oss.ImgHost + path
  54. return resourceUrl, err
  55. }
  56. func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
  57. useSsl := "1"
  58. if !global.CONFIG.Oss.DisableSSL {
  59. useSsl = `0`
  60. }
  61. token.AccessKeyId = global.CONFIG.Oss.AccessKeyId
  62. token.SecretKeyId = global.CONFIG.Oss.AccessKeySecret
  63. token.Endpoint = global.CONFIG.Oss.EndPoint
  64. token.ImgHost = global.CONFIG.Oss.ImgHost
  65. token.Bucketname = global.CONFIG.Oss.BucketName
  66. token.UseSSL = useSsl
  67. token.RegionId = global.CONFIG.Oss.RegionId
  68. token.Port = global.CONFIG.Oss.Port
  69. return
  70. }