Files
web_template/internal/storage/storage.go
2026-07-10 10:06:48 +00:00

54 lines
1.8 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 storage
import (
"io"
"log"
"gotest/internal/config"
)
// Storage 文件存储抽象接口,统一本地存储、MinIO、腾讯云 COS 的操作
type Storage interface {
// Upload 上传文件,key 为存储路径,返回可访问的 URL
Upload(key string, reader io.Reader, contentType string) (string, error)
// Delete 删除指定 key 的文件
Delete(key string) error
// GetURL 获取指定 key 的访问 URL
GetURL(key string) string
}
// NewStorage 根据配置创建存储实例
// 根据 cfg.Type 返回 local/minio/cos 实现,默认 local
// 当 minio/cos 关键配置缺失或初始化失败时,降级为本地存储并打印提示日志
func NewStorage(cfg *config.StorageConfig) Storage {
switch cfg.Type {
case "minio":
// 关键配置(endpoint/accesskey/secretkey)缺失时降级为本地存储
if cfg.MinIO.Endpoint == "" || cfg.MinIO.AccessKey == "" || cfg.MinIO.SecretKey == "" {
log.Println("MinIO 关键配置(endpoint/accesskey/secretkey)缺失,降级使用本地存储")
return NewLocalStorage(&cfg.Local)
}
s, err := NewMinIOStorage(&cfg.MinIO)
if err != nil {
log.Printf("MinIO 存储初始化失败: %v,降级使用本地存储\n", err)
return NewLocalStorage(&cfg.Local)
}
return s
case "cos":
// 关键配置(secretid/secretkey)缺失时降级为本地存储
if cfg.COS.SecretID == "" || cfg.COS.SecretKey == "" {
log.Println("COS 关键配置(secretid/secretkey)缺失,降级使用本地存储")
return NewLocalStorage(&cfg.Local)
}
s, err := NewCOSStorage(&cfg.COS)
if err != nil {
log.Printf("COS 存储初始化失败: %v,降级使用本地存储\n", err)
return NewLocalStorage(&cfg.Local)
}
return s
default:
// 默认使用本地存储
return NewLocalStorage(&cfg.Local)
}
}