2.0 KiB
2.0 KiB
配置管理
MengStack 使用 Viper 进行配置管理,支持多来源、分层配置。
配置优先级
从高到低:
- 环境变量(
MENGSTACK_前缀) .env文件configs/config.yaml- 默认值
配置文件
configs/config.yaml
server:
port: 2222
mode: debug # debug / release / test
database:
host: localhost
port: 5432
name: mengstack
user: postgres
password: ""
sslmode: disable
redis:
host: localhost
port: 6379
password: ""
db: 0
jwt:
secret: "change-me-in-production"
access_ttl: 7200 # 2 hours
refresh_ttl: 604800 # 7 days
log:
level: debug # debug / info / warn / error
format: console # console / json
环境变量覆盖
所有配置项都可以通过环境变量覆盖,规则:
- 前缀
MENGSTACK_ - 大写
- 用
_连接层级
# 等价于 server.port: 3000
export MENGSTACK_SERVER_PORT=3000
# 等价于 database.host: db.example.com
export MENGSTACK_DB_HOST=db.example.com
# 等价于 jwt.secret: my-secret
export MENGSTACK_JWT_SECRET=my-secret
代码中使用
type Config struct {
Server ServerConfig
Database DatabaseConfig
Redis RedisConfig
JWT JWTConfig
Log LogConfig
}
func Load() (*Config, error) {
v := viper.New()
v.SetConfigFile("configs/config.yaml")
v.SetEnvPrefix("MENGSTACK")
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
if err := v.ReadInConfig(); err != nil {
return nil, err
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return nil, err
}
return &cfg, nil
}
最佳实践
- 不要硬编码:所有可变配置走 Viper
- 生产环境用环境变量:敏感信息(密码、密钥)不写入代码仓库
- 提供合理默认值:开发环境零配置即可启动
- 使用
.env.example:提供配置模板,方便新人上手