minio.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package services
  2. import (
  3. "context"
  4. "errors"
  5. "eta_gn/eta_report/utils"
  6. "github.com/minio/minio-go/v7"
  7. "github.com/minio/minio-go/v7/pkg/credentials"
  8. "log"
  9. "os"
  10. "time"
  11. )
  12. type MinioOss struct{}
  13. func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
  14. defer func() {
  15. _ = os.Remove(filePath)
  16. }()
  17. if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
  18. return "0", errors.New("MinIo信息未配置")
  19. }
  20. ctx := context.Background()
  21. endpoint := utils.MinIoEndpoint
  22. accessKeyID := utils.MinIoAccessKeyId
  23. secretAccessKey := utils.MinIoAccessKeySecret
  24. useSSL := false
  25. if utils.MinIoUseSSL == "true" {
  26. useSSL = true
  27. }
  28. minioClient, err := minio.New(endpoint, &minio.Options{
  29. Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
  30. Secure: useSSL,
  31. })
  32. if err != nil {
  33. log.Fatalln(err)
  34. return "1", err
  35. }
  36. bucketName := utils.MinIoBucketname
  37. exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
  38. if errBucketExists == nil && exists {
  39. log.Printf("We already own %s\n", bucketName)
  40. } else {
  41. log.Fatalln(err)
  42. return "2", err
  43. }
  44. path := savePath
  45. if savePath == "" {
  46. path = utils.MinIoUploadDir + 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 := utils.MinIoImghost + path
  54. return resourceUrl, err
  55. }
  56. func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
  57. token.AccessKeyId = utils.MinIoAccessKeyId
  58. token.SecretKeyId = utils.MinIoAccessKeySecret
  59. token.Endpoint = utils.MinIoEndpoint
  60. token.ImgHost = utils.MinIoImghost
  61. token.Bucketname = utils.MinIoBucketname
  62. token.UseSSL = utils.MinIoUseSSL
  63. token.RegionId = utils.MinIoRegion
  64. token.Port = utils.MinIoPort
  65. return
  66. }