Skip to content

配置管理 ​

MengStack 使用 Viper 进行配置管理,支持多来源、分层配置。

配置优先级 ​

从高到低:

  1. 环境变量(MENGSTACK_ 前缀)
  2. .env 文件
  3. configs/config.yaml
  4. 默认值

配置文件 ​

configs/config.yaml ​

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_
  • 大写
  • 用 _ 连接层级
bash
# 等价于 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

代码中使用 ​

go
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
}

最佳实践 ​

  1. 不要硬编码:所有可变配置走 Viper
  2. 生产环境用环境变量:敏感信息(密码、密钥)不写入代码仓库
  3. 提供合理默认值:开发环境零配置即可启动
  4. 使用 .env.example:提供配置模板,方便新人上手