Files
workspace/code/base-project/base-go-v2/internal/config/app.go
T
2025-10-31 22:35:20 +08:00

81 lines
1.5 KiB
Go

package config
import (
"base-go-v2/internal/types"
"fmt"
"time"
"github.com/spf13/viper"
)
// App 全局唯一配置实例
var App *types.AppConfig
// init 初始化默认值
func init() {
App = &types.AppConfig{
Server: types.ServerConfig{
Port: 8080,
},
JWT: types.JWTConfig{
Secret: "default_secret",
Expiry: time.Hour,
},
Db: types.DbConfig{
MaxOpenConns: 10,
MaxIdleConns: 5,
ConnMaxLifetime: 30 * time.Minute,
},
Snowflake: types.SnowflakeConfig{
DatacenterID: 1,
WorkerID: 1,
},
Log: types.LogConfig{
Dir: "logs",
Level: "debug",
Format: "json",
Daily: true,
MaxDays: 30,
Caller: true,
LevelDirs: true,
Console: true,
},
}
}
// InitAppConfig 初始化配置
func InitAppConfig(configPath string) error {
if configPath == "" {
fmt.Println("⚠️ 使用默认配置")
return nil
}
v := viper.New()
v.SetConfigFile(configPath)
v.SetConfigType("yaml")
if err := v.ReadInConfig(); err != nil {
return err
}
// 逐字段解码,缺失字段保留默认值
if err := v.UnmarshalKey("server", &App.Server); err != nil {
return err
}
if err := v.UnmarshalKey("jwt", &App.JWT); err != nil {
return err
}
if err := v.UnmarshalKey("snowflake", &App.Snowflake); err != nil {
return err
}
if err := v.UnmarshalKey("db", &App.Db); err != nil {
return err
}
if err := v.UnmarshalKey("log", &App.Log); err != nil {
return err
}
fmt.Printf("✅ 初始化 %s 配置成功\n", configPath)
return nil
}