Skip to content

Commit

Permalink
Merge pull request #16 from SugarMGP/dev
Browse files Browse the repository at this point in the history
refactor: 简化 Minio 相关代码
  • Loading branch information
qianqianzyk authored Nov 21, 2024
2 parents 813b8e1 + 3bc4224 commit 4e8550f
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 56 deletions.
10 changes: 4 additions & 6 deletions app/apiException/apiException.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@ var (
NotLogin = NewError(200509, log.LevelInfo, "未登录")
NotPermission = NewError(200510, log.LevelInfo, "该用户无权限")
ResourceNotFound = NewError(200511, log.LevelInfo, "访问的资源不存在")
AdminKeyError = NewError(200513, log.LevelInfo, "管理员注册密钥错误")
AdminAlreadyExisted = NewError(200514, log.LevelInfo, "管理员账号已存在")
GetFileInfoError = NewError(200515, log.LevelInfo, "获取文件信息失败")
UploadFileError = NewError(200516, log.LevelInfo, "上传文件失败")
SetFileNameError = NewError(200517, log.LevelInfo, "文件重命名失败")
FileSizeExceedError = NewError(200518, log.LevelInfo, "文件大小超限")
AdminKeyError = NewError(200512, log.LevelInfo, "管理员注册密钥错误")
AdminAlreadyExisted = NewError(200513, log.LevelInfo, "管理员账号已存在")
UploadFileError = NewError(200514, log.LevelError, "上传文件失败")
FileSizeExceedError = NewError(200515, log.LevelInfo, "文件大小超限")

NotInit = NewError(200404, log.LevelWarn, http.StatusText(http.StatusNotFound))
NotFound = NewError(200404, log.LevelWarn, http.StatusText(http.StatusNotFound))
Expand Down
12 changes: 3 additions & 9 deletions app/controllers/objectController/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func UploadFile(c *gin.Context) {
return
}
if err != nil {
apiException.AbortWithException(c, apiException.GetFileInfoError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
_, err = file.Seek(0, io.SeekStart)
Expand All @@ -60,15 +60,9 @@ func UploadFile(c *gin.Context) {
return
}

// 文件重命名
ossSavePath, err := objectService.SetFileName(uploadType, fileExt)
if err != nil {
apiException.AbortWithException(c, apiException.SetFileNameError, err)
return
}

// 上传文件
objectUrl, err := objectService.PutPersistentObject(ossSavePath, file, fileHeader.Size, contentType)
objectKey := objectService.GetObjectKey(uploadType, fileExt)
objectUrl, err := objectService.PutObject(objectKey, file, fileHeader.Size, contentType)
if err != nil {
apiException.AbortWithException(c, apiException.UploadFileError, err)
return
Expand Down
23 changes: 12 additions & 11 deletions app/services/objectService/minioObjectService.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package objectService
import (
"context"
"io"
"strings"

"4u-go/config/objectStorage"
"github.com/minio/minio-go/v7"
Expand All @@ -12,8 +13,8 @@ import (
// ms 是全局的 MinioService 实例
var ms = &objectStorage.MinioService

// PutPersistentObject 用于上传持久化对象
func PutPersistentObject(objectKey string, reader io.Reader, size int64, contentType string) (string, error) {
// PutObject 用于上传对象
func PutObject(objectKey string, reader io.Reader, size int64, contentType string) (string, error) {
opts := minio.PutObjectOptions{ContentType: contentType}
_, err := (*ms).Client.PutObject(context.Background(), (*ms).Bucket, objectKey, reader, size, opts)
if err != nil {
Expand All @@ -24,17 +25,17 @@ func PutPersistentObject(objectKey string, reader io.Reader, size int64, content

// PutTemporaryObject 用于上传临时对象
func PutTemporaryObject(objectKey string, reader io.Reader, size int64, contentType string) (string, error) {
opts := minio.PutObjectOptions{ContentType: contentType}
objectName := (*ms).TempDir + objectKey
_, err := (*ms).Client.PutObject(context.Background(), (*ms).Bucket, objectName, reader, size, opts)
if err != nil {
return "", err
}
return (*ms).Domain + (*ms).Bucket + "/" + objectName, nil
return PutObject((*ms).TempDir+objectKey, reader, size, contentType)
}

// DeleteObjectByUrl 从 Url 中获取 objectKey 并删除对应对象
func DeleteObjectByUrl(fullUrl string) error {
objectKey := strings.TrimPrefix(fullUrl, (*ms).Domain+(*ms).Bucket+"/")
return DeleteObject(objectKey)
}

// DelObject 用于删除相应对象
func DelObject(objectKey string) error {
// DeleteObject 用于删除相应对象
func DeleteObject(objectKey string) error {
err := (*ms).Client.RemoveObject(
context.Background(),
(*ms).Bucket,
Expand Down
34 changes: 4 additions & 30 deletions app/services/objectService/objectService.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
package objectService

import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"mime/multipart"
"strings"
"time"

"github.com/dustin/go-humanize"
"github.com/gabriel-vasile/mimetype"
uuid "github.com/satori/go.uuid"
)

var (
Expand Down Expand Up @@ -50,33 +48,9 @@ func GetFileInfo(
return mimeType, mimeExt, nil
}

// SetFileName 将文件重命名
func SetFileName(uploadType string, fileExt string) (string, error) {
now := time.Now()
timestamp := now.UnixNano() / 1e6

randomBytes := make([]byte, 16)
if _, err := rand.Read(randomBytes); err != nil {
return "", errors.New("failed to generate random bytes")
}

randomString := hex.EncodeToString(randomBytes)
randomPath := fmt.Sprintf("%d%s", timestamp, randomString)
if randomPath == "" {
return "", errors.New("failed to generate random path")
}

ossSavePath := fmt.Sprintf("%s/%d/%s%s", uploadType, now.Year(), randomPath, fileExt)
if ossSavePath == "" {
return "", errors.New("failed to generate ossSavePath")
}

return ossSavePath, nil
}

// RemoveDomain 去除 URL 的域名部分
func RemoveDomain(fullUrl string, domain string, bucket string) string {
return strings.TrimPrefix(strings.TrimPrefix(fullUrl, domain), bucket+"/")
// GetObjectKey 通过 UUID 作为文件名并返回 ObjectKey
func GetObjectKey(uploadType string, fileExt string) string {
return fmt.Sprintf("%s/%d/%s%s", uploadType, time.Now().Year(), uuid.NewV1().String(), fileExt)
}

// checkFileSize 检查文件大小
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ require (
github.com/go-resty/resty/v2 v2.16.0
github.com/minio/minio-go/v7 v7.0.80
github.com/pkg/errors v0.9.1
github.com/satori/go.uuid v1.2.0
github.com/silenceper/wechat/v2 v2.1.7
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.19.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ github.com/sagikazarmark/locafero v0.6.0 h1:ON7AQg37yzcRPU69mt7gwhFEBwxI6P9T4Qu3
github.com/sagikazarmark/locafero v0.6.0/go.mod h1:77OmuIc6VTraTXKXIs/uvUxKGUXjE1GbemJYHqdNjX0=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/silenceper/wechat/v2 v2.1.7 h1:v4AC4pa6NRm7Pa2FJnmWABOxZ9hx3IIo20xKT4t1msY=
github.com/silenceper/wechat/v2 v2.1.7/go.mod h1:7Iu3EhQYVtDUJAj+ZVRy8yom75ga7aDWv8RurLkVm0s=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
Expand Down

0 comments on commit 4e8550f

Please sign in to comment.