minio.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package services
  2. import (
  3. "context"
  4. "errors"
  5. "eta_gn/eta_api/utils"
  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. func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
  14. if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
  15. return "0", errors.New("MinIo信息未配置")
  16. }
  17. ctx := context.Background()
  18. endpoint := utils.MinIoEndpoint
  19. if utils.MinIoBackEndpoint != "" {
  20. endpoint = utils.MinIoBackEndpoint
  21. }
  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. err = fmt.Errorf("BucketExists: %v; err: %v", exists, errBucketExists)
  40. return "2", err
  41. }
  42. path := savePath
  43. if savePath == "" {
  44. path = utils.MinIoUploadDir + time.Now().Format("200601/20060102/") + fileName
  45. }
  46. _, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
  47. if err != nil {
  48. log.Fatalln(err)
  49. return "3", err
  50. }
  51. resourceUrl := utils.MinIoImghost + path
  52. return resourceUrl, err
  53. }
  54. func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
  55. token.AccessKeyId = utils.MinIoAccessKeyId
  56. token.SecretKeyId = utils.MinIoAccessKeySecret
  57. token.Endpoint = utils.MinIoEndpoint
  58. token.ImgHost = utils.MinIoImghost
  59. token.Bucketname = utils.MinIoBucketname
  60. token.UseSSL = utils.MinIoUseSSL
  61. token.RegionId = utils.MinIoRegion
  62. token.Port = utils.MinIoPort
  63. return
  64. }