fusenapi/server/upload/internal/logic/uploadfilebackendlogic.go

131 lines
3.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package logic
import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/check"
"fusenapi/utils/format"
"time"
"context"
"fusenapi/server/upload/internal/svc"
"fusenapi/server/upload/internal/types"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/zeromicro/go-zero/core/logx"
)
type UploadFileBackendLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUploadFileBackendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileBackendLogic {
return &UploadFileBackendLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// UploadFileBackend 这个函数接收一个文件上传请求和用户信息,处理文件上传,并返回响应
func (l *UploadFileBackendLogic) UploadFileBackend(req *types.RequestUploadFileBackend, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
// 检查用户是否是旁观者,旁观者没有文件上传权限
if userinfo.IsOnlooker() {
// 如果是,返回未授权的错误码
return resp.SetStatus(basic.CodeUnAuth)
}
// 定义用户ID和S3键名格式
var uid int64
var keytype format.TypeFormatS3KeyName
// 检查用户是否是游客
if userinfo.IsGuest() {
// 如果是使用游客ID和游客键名格式
uid = userinfo.GuestId
keytype = format.TypeS3KeyGuest
} else {
// 否则使用用户ID和用户键名格式
uid = userinfo.UserId
keytype = format.TypeS3KeyUser
}
// 设置AWS会话的区域
l.svcCtx.AwsSession.Config.Region = aws.String("us-west-1")
// 创建新的S3服务实例
svc := s3.New(l.svcCtx.AwsSession)
// 检查类别是否合法
if !check.CheckCategory(req.Category) {
// 如果不合法,返回类别错误的错误码
return resp.SetStatus(basic.CodeS3CategoryErr)
}
// 定义S3请求和当前时间
var s3req *request.Request
now := time.Now()
// 格式化类别
category := format.TypeCategory(req.Category)
// 格式化S3对象键名
ObjectKey := aws.String(format.FormatS3KeyName(
keytype,
uid,
now,
l.svcCtx.Config.Env,
category,
req.File.Filename,
))
// 定义存储桶名称
var bucketName *string
// 根据类别选择存储桶
switch category {
case format.TCategoryRenderMegre:
bucketName = basic.TempfileBucketName
default:
bucketName = basic.StorageBucketName
}
// 创建S3对象存储请求
s3req, _ = svc.PutObjectRequest(
&s3.PutObjectInput{
Bucket: bucketName,
Key: ObjectKey,
},
)
// 设置请求体为文件数据
s3req.SetBufferBody(req.File.Data)
// 发送请求
err := s3req.Send()
// 检查是否有错误
if err != nil {
// 如果有,打印错误并返回错误码
logx.Error(err)
return resp.SetStatus(basic.CodeS3PutObjectRequestErr)
}
// 打印请求URL
logx.Info(s3req.HTTPRequest.URL.String())
// 返回成功的响应和上传URL
return resp.SetStatus(basic.CodeOK, map[string]interface{}{
"upload_url": s3req.HTTPRequest.URL.String(),
})
}