This commit is contained in:
oneao committed 2026-04-02 22:07:21 +08:00
1 parent ae0d245605
commit 4725ee75ca
26 files changed
+1089 -67

No files matched your search

@@ -1,7 +1,11 @@
package config
import "time"
type Config struct {
App AppConfig `mapstructure:"app"`
JWT JwtConfig `mapstructure:"jwt"`
UniqueID UniqueIDConfig `mapstructure:"unique_id"`
Postgres PostgresConfig `mapstructure:"postgres"`
}
@@ -11,11 +15,24 @@ type AppConfig struct {
}
type PostgresConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Dbname string `mapstructure:"dbname"`
SslMode bool `mapstructure:"ssl_mode"`
TimeZone string `mapstructure:"timezone"`
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Dbname string `mapstructure:"dbname"`
SslMode bool `mapstructure:"ssl_mode"`
TimeZone string `mapstructure:"timezone"`
MaxOpenConns int32 `mapstructure:"max_open_conns"`
MaxIdleConns int32 `mapstructure:"max_idle_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
}
type JwtConfig struct {
Secret string `mapstructure:"secret"`
AccessExpiry time.Duration `mapstructure:"access_expiry"`
}
type UniqueIDConfig struct {
DataCenterID uint16 `mapstructure:"datacenter_id"`
WorkerID uint16 `mapstructure:"worker_id"`
}
@@ -14,12 +14,19 @@ func Load() (*Config, error) {
v := viper.New()
v.SetConfigType("yaml")
// ✅ 默认值
setDefaults(v)
// ✅ 支持环境变量(如 APP_PORT → app.port)
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// 基础配置
v.AddConfigPath("configs")
v.SetConfigName("config")
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("read base config failed: %w", err)
return nil, fmt.Errorf("读取基础配置失败: %w", err)
}
// 环境配置(覆盖)
@@ -27,20 +34,30 @@ func Load() (*Config, error) {
v.SetConfigName(envConfigName)
if err := v.MergeInConfig(); err != nil {
// dev 允许没有文件,prod 建议必须存在
// dev 可以没有,prod 必须有
if env == "prod" {
return nil, fmt.Errorf("read env config failed: %w", err)
return nil, fmt.Errorf("读取环境配置失败(%s): %w", env, err)
}
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("unmarshal config failed: %w", err)
return nil, fmt.Errorf("解析配置失败: %w", err)
}
return &cfg, nil
}
// ✅ 默认值统一在这里管理
func setDefaults(v *viper.Viper) {
v.SetDefault("app.name", "allapp-go")
v.SetDefault("app.port", 8080)
// 可以继续扩展
v.SetDefault("unique_id.datacenter_id", 1)
v.SetDefault("unique_id.worker_id", 1)
}
func getEnv(key, defaultVal string) string {
val := os.Getenv(key)
if val == "" {