Files
junhong_cmp_fiber/pkg/storage/service.go
huang 45aa7deb87
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m33s
feat: 添加环境变量管理工具和部署配置改版
主要改动:
- 新增交互式环境配置脚本 (scripts/setup-env.sh)
- 新增本地启动快捷脚本 (scripts/run-local.sh)
- 新增环境变量模板文件 (.env.example)
- 部署模式改版:使用嵌入式配置 + 环境变量覆盖
- 添加对象存储功能支持
- 改进 IoT 卡片导入任务
- 优化 OpenAPI 文档生成
- 删除旧的配置文件,改用嵌入式默认配置
2026-01-26 10:28:29 +08:00

113 lines
2.2 KiB
Go

package storage
import (
"context"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/google/uuid"
"github.com/break/junhong_cmp_fiber/pkg/config"
)
type Service struct {
provider Provider
config *config.StorageConfig
}
func NewService(provider Provider, cfg *config.StorageConfig) *Service {
return &Service{
provider: provider,
config: cfg,
}
}
func (s *Service) GenerateFileKey(purpose, fileName string) (string, error) {
mapping, ok := PurposeMappings[purpose]
if !ok {
return "", fmt.Errorf("不支持的文件用途: %s", purpose)
}
ext := filepath.Ext(fileName)
if ext == "" {
ext = ".bin"
}
now := time.Now()
id := uuid.New().String()
key := fmt.Sprintf("%s/%04d/%02d/%02d/%s%s",
mapping.Prefix,
now.Year(),
now.Month(),
now.Day(),
id,
strings.ToLower(ext),
)
return key, nil
}
func (s *Service) GetUploadURL(ctx context.Context, purpose, fileName, contentType string) (*PresignResult, error) {
fileKey, err := s.GenerateFileKey(purpose, fileName)
if err != nil {
return nil, err
}
if contentType == "" {
if mapping, ok := PurposeMappings[purpose]; ok && mapping.ContentType != "" {
contentType = mapping.ContentType
} else {
contentType = "application/octet-stream"
}
}
expires := s.config.Presign.UploadExpires
if expires == 0 {
expires = 15 * time.Minute
}
url, err := s.provider.GetUploadURL(ctx, fileKey, contentType, expires)
if err != nil {
return nil, err
}
return &PresignResult{
URL: url,
FileKey: fileKey,
ExpiresIn: int(expires.Seconds()),
}, nil
}
func (s *Service) GetDownloadURL(ctx context.Context, fileKey string) (*PresignResult, error) {
expires := s.config.Presign.DownloadExpires
if expires == 0 {
expires = 24 * time.Hour
}
url, err := s.provider.GetDownloadURL(ctx, fileKey, expires)
if err != nil {
return nil, err
}
return &PresignResult{
URL: url,
FileKey: fileKey,
ExpiresIn: int(expires.Seconds()),
}, nil
}
func (s *Service) DownloadToTemp(ctx context.Context, fileKey string) (string, func(), error) {
return s.provider.DownloadToTemp(ctx, fileKey)
}
func (s *Service) Provider() Provider {
return s.provider
}
func (s *Service) Bucket() string {
return s.config.S3.Bucket
}