refactor: 移除全局单例、修复分层违规、统一错误与响应
This commit is contained in:
@@ -1,55 +1,8 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"carrotskin/pkg/config"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
// clientInstance 全局存储客户端实例
|
||||
clientInstance *StorageClient
|
||||
// once 确保只初始化一次
|
||||
once sync.Once
|
||||
// initError 初始化错误
|
||||
initError error
|
||||
)
|
||||
|
||||
// Init 初始化存储客户端(线程安全,只会执行一次)
|
||||
func Init(cfg config.RustFSConfig) error {
|
||||
once.Do(func() {
|
||||
clientInstance, initError = NewStorage(cfg)
|
||||
if initError != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
return initError
|
||||
}
|
||||
|
||||
// GetClient 获取存储客户端实例(线程安全)
|
||||
func GetClient() (*StorageClient, error) {
|
||||
if clientInstance == nil {
|
||||
return nil, fmt.Errorf("存储客户端未初始化,请先调用 storage.Init()")
|
||||
}
|
||||
return clientInstance, nil
|
||||
}
|
||||
|
||||
// MustGetClient 获取存储客户端实例,如果未初始化则panic
|
||||
func MustGetClient() *StorageClient {
|
||||
client, err := GetClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 本文件原包含基于 sync.Once 的全局单例(Init/GetClient/MustGetClient)。
|
||||
//
|
||||
// 在 DI 迁移(阶段4)后,全局单例已被移除。Storage 客户端由 fx.Provide(storage.NewStorage)
|
||||
// 构造,通过构造函数参数注入到各消费者。
|
||||
//
|
||||
// 存储客户端构造逻辑见 minio.go 的 NewStorage()。
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"carrotskin/pkg/config"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGetClient_NotInitialized 测试未初始化时获取存储客户端
|
||||
func TestGetClient_NotInitialized(t *testing.T) {
|
||||
_, err := GetClient()
|
||||
if err == nil {
|
||||
t.Error("未初始化时应该返回错误")
|
||||
}
|
||||
|
||||
expectedError := "存储客户端未初始化,请先调用 storage.Init()"
|
||||
if err.Error() != expectedError {
|
||||
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMustGetClient_Panic 测试MustGetClient在未初始化时panic
|
||||
func TestMustGetClient_Panic(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Error("MustGetClient 应该在未初始化时panic")
|
||||
}
|
||||
}()
|
||||
|
||||
_ = MustGetClient()
|
||||
}
|
||||
|
||||
// TestInit_Storage 测试存储客户端初始化逻辑
|
||||
func TestInit_Storage(t *testing.T) {
|
||||
cfg := config.RustFSConfig{
|
||||
Endpoint: "http://localhost:9000",
|
||||
AccessKey: "minioadmin",
|
||||
SecretKey: "minioadmin",
|
||||
UseSSL: false,
|
||||
Buckets: map[string]string{
|
||||
"avatars": "avatars",
|
||||
"textures": "textures",
|
||||
},
|
||||
}
|
||||
|
||||
// 验证Init函数存在且可调用
|
||||
// 注意:实际连接可能失败,这是可以接受的
|
||||
err := Init(cfg)
|
||||
if err != nil {
|
||||
t.Logf("Init() 返回错误(可能正常,如果存储服务未运行): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user