63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
|
|
package oss
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"fmt"
|
||
|
|
"github.com/google/uuid"
|
||
|
|
oss2 "legalgo-BE-go/internal/accessor/oss"
|
||
|
|
"legalgo-BE-go/internal/domain/oss"
|
||
|
|
"path"
|
||
|
|
"strconv"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/go-playground/validator/v10"
|
||
|
|
)
|
||
|
|
|
||
|
|
type OssService struct {
|
||
|
|
ossRepo oss2.OSSRepository
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewOSSService(ossRepo oss2.OSSRepository) OSSService {
|
||
|
|
return &OssService{
|
||
|
|
ossRepo: ossRepo,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *OssService) UploadFile(ctx context.Context, req *oss.UploadFileRequest) (*oss.UploadFileResponse, error) {
|
||
|
|
file := req.FileHeader
|
||
|
|
req.FileSize = file.Size
|
||
|
|
req.Ext = path.Ext(file.Filename)
|
||
|
|
validate := validator.New()
|
||
|
|
if err := validate.Struct(req); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
// Open the file and read its content
|
||
|
|
srcFile, err := file.Open()
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
defer srcFile.Close()
|
||
|
|
|
||
|
|
fileContent := make([]byte, file.Size)
|
||
|
|
_, err = srcFile.Read(fileContent)
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
filePath := fmt.Sprintf("%v/%v%v", req.FolderName, s.GenerateFileName(), req.Ext)
|
||
|
|
fileUrl, err := s.ossRepo.UploadFile(ctx, filePath, fileContent)
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
return &oss.UploadFileResponse{
|
||
|
|
FilePath: filePath,
|
||
|
|
FileUrl: fileUrl,
|
||
|
|
}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *OssService) GenerateFileName() string {
|
||
|
|
return fmt.Sprintf("%v-%v", uuid.New(), strconv.Itoa(int(time.Now().Unix())))
|
||
|
|
}
|