Add internal/storage/storage.go
This commit is contained in:
53
internal/storage/storage.go
Normal file
53
internal/storage/storage.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user