u
This commit is contained in:
1 parent
91ae4cb474
commit
b116690769
14 files changed
+669
-56
No files matched your search
@@ -2,35 +2,54 @@ package config
|
||||
|
||||
import (
|
||||
"base-go-v2/internal/types"
|
||||
"github.com/spf13/viper"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// App 全局唯一导出配置实例,初始化默认值
|
||||
var App = &types.AppConfig{
|
||||
Server: types.AppConfig{}.Server,
|
||||
JWT: types.AppConfig{}.JWT,
|
||||
Db: types.AppConfig{}.Db,
|
||||
Snowflake: types.AppConfig{}.Snowflake,
|
||||
}
|
||||
// App 全局唯一配置实例
|
||||
var App *types.AppConfig
|
||||
|
||||
// 给部分字段设置默认值
|
||||
// init 初始化默认值
|
||||
func init() {
|
||||
App.Server.Port = 8080
|
||||
App.JWT.Secret = "default_secret"
|
||||
App.JWT.Expiry = time.Hour
|
||||
|
||||
// 数据库只给连接池默认值
|
||||
App.Db.MaxOpenConns = 10
|
||||
App.Db.MaxIdleConns = 5
|
||||
App.Db.ConnMaxLifetime = 30 * time.Minute
|
||||
|
||||
App.Snowflake.DatacenterID = 1
|
||||
App.Snowflake.WorkerID = 1
|
||||
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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// InitApplicationConfig 初始化配置
|
||||
func InitApplicationConfig(configPath string) error {
|
||||
// InitAppConfig 初始化配置
|
||||
func InitAppConfig(configPath string) error {
|
||||
if configPath == "" {
|
||||
fmt.Println("⚠️ 使用默认配置")
|
||||
return nil
|
||||
}
|
||||
|
||||
v := viper.New()
|
||||
v.SetConfigFile(configPath)
|
||||
v.SetConfigType("yaml")
|
||||
@@ -39,21 +58,23 @@ func InitApplicationConfig(configPath string) error {
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user