refactor: 移除不必要的配置依赖,简化上传URL生成逻辑并添加公开访问URL支持

This commit is contained in:
lan
2025-12-02 11:22:14 +08:00
parent 13bab28926
commit 23be1c563d
12 changed files with 478 additions and 173 deletions

View File

@@ -13,8 +13,9 @@ import (
// StorageClient S3兼容对象存储客户端包装 (支持RustFS、MinIO等)
type StorageClient struct {
client *minio.Client
buckets map[string]string
client *minio.Client
buckets map[string]string
publicURL string // 公开访问URL前缀
}
// NewStorage 创建新的对象存储客户端 (S3兼容支持RustFS)
@@ -41,9 +42,21 @@ func NewStorage(cfg config.RustFSConfig) (*StorageClient, error) {
}
}
// 构建公开访问URL
publicURL := cfg.PublicURL
if publicURL == "" {
// 如果未配置 PublicURL使用 Endpoint 构建
protocol := "http"
if cfg.UseSSL {
protocol = "https"
}
publicURL = fmt.Sprintf("%s://%s", protocol, cfg.Endpoint)
}
storageClient := &StorageClient{
client: client,
buckets: cfg.Buckets,
client: client,
buckets: cfg.Buckets,
publicURL: publicURL,
}
return storageClient, nil
@@ -81,7 +94,7 @@ type PresignedPostPolicyResult struct {
// GeneratePresignedPostURL 生成预签名POST URL (支持表单上传)
// 注意使用时必须确保file字段是表单的最后一个字段
func (s *StorageClient) GeneratePresignedPostURL(ctx context.Context, bucketName, objectName string, minSize, maxSize int64, expires time.Duration, useSSL bool, endpoint string) (*PresignedPostPolicyResult, error) {
func (s *StorageClient) GeneratePresignedPostURL(ctx context.Context, bucketName, objectName string, minSize, maxSize int64, expires time.Duration) (*PresignedPostPolicyResult, error) {
// 创建上传策略
policy := minio.NewPostPolicy()
@@ -105,12 +118,8 @@ func (s *StorageClient) GeneratePresignedPostURL(ctx context.Context, bucketName
// 注意在Go中直接delete不存在的key是安全的
delete(formData, "bucket")
// 构造文件的永久访问URL
protocol := "http"
if useSSL {
protocol = "https"
}
fileURL := fmt.Sprintf("%s://%s/%s/%s", protocol, endpoint, bucketName, objectName)
// 使用配置的公开访问URL构造文件的永久访问URL
fileURL := s.BuildFileURL(bucketName, objectName)
return &PresignedPostPolicyResult{
PostURL: postURL.String(),
@@ -118,3 +127,13 @@ func (s *StorageClient) GeneratePresignedPostURL(ctx context.Context, bucketName
FileURL: fileURL,
}, nil
}
// BuildFileURL 构建文件的公开访问URL
func (s *StorageClient) BuildFileURL(bucketName, objectName string) string {
return fmt.Sprintf("%s/%s/%s", s.publicURL, bucketName, objectName)
}
// GetPublicURL 获取公开访问URL前缀
func (s *StorageClient) GetPublicURL() string {
return s.publicURL
}