12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package oss
- import (
- "context"
- "errors"
- "eta/eta_email_analysis/global"
- "fmt"
- "github.com/minio/minio-go/v7"
- "github.com/minio/minio-go/v7/pkg/credentials"
- "log"
- "time"
- )
- type MinioOss struct{}
- // UploadFile 上传文件
- func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
- if global.CONFIG.Oss.AccessKeyId == `` || global.CONFIG.Oss.AccessKeySecret == `` {
- return "0", errors.New("MinIo信息未配置")
- }
- ctx := context.Background()
- // 此处兼容一下前后端endpoint不一致的情况, 前端用minio_endpoint后端用minio_back_endpoint, minio_back_endpoint为空则都取前者
- endpoint := global.CONFIG.Oss.EndPoint
- if global.CONFIG.Oss.BackEndPoint != "" {
- endpoint = global.CONFIG.Oss.BackEndPoint
- }
- accessKeyID := global.CONFIG.Oss.AccessKeyId
- secretAccessKey := global.CONFIG.Oss.AccessKeySecret
- useSSL := false
- if !global.CONFIG.Oss.DisableSSL {
- useSSL = true
- }
- minioClient, err := minio.New(endpoint, &minio.Options{
- Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
- Secure: useSSL,
- })
- if err != nil {
- log.Fatalln(err)
- return "1", err
- }
- bucketName := global.CONFIG.Oss.BucketName
- exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
- if errBucketExists != nil || !exists {
- err = fmt.Errorf("BucketExists: %v; err: %v", exists, errBucketExists)
- return "2", err
- }
- path := savePath
- if savePath == "" {
- path = global.CONFIG.Oss.UploadDir + time.Now().Format("200601/20060102/") + fileName
- }
- _, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
- if err != nil {
- log.Fatalln(err)
- return "3", err
- }
- resourceUrl := global.CONFIG.Oss.ImgHost + path
- return resourceUrl, err
- }
- func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
- useSsl := "1"
- if !global.CONFIG.Oss.DisableSSL {
- useSsl = `0`
- }
- token.AccessKeyId = global.CONFIG.Oss.AccessKeyId
- token.SecretKeyId = global.CONFIG.Oss.AccessKeySecret
- token.Endpoint = global.CONFIG.Oss.EndPoint
- token.ImgHost = global.CONFIG.Oss.ImgHost
- token.Bucketname = global.CONFIG.Oss.BucketName
- token.UseSSL = useSsl
- token.RegionId = global.CONFIG.Oss.RegionId
- token.Port = global.CONFIG.Oss.Port
- return
- }
|