mengstack-website/guide/configuration.md
SoftUnis ecb29e0aa4 初始化 MengStack 官方网站仓库
包含 VitePress 文档站完整源码及全新自定义首页设计:
- 自定义首页组件 (Home.vue):Hero + 终端动效 + 核心能力 + 架构展示 + 快速开始 + CTA
- 自定义 Layout.vue:首页/文档页布局切换
- 金铜色品牌主题样式
- 完整文档页面(指南、API、更新日志、演示、社区)
- SEO 配置(sitemap、robots、meta 标签)
2026-10-02 23:37:25 +08:00

103 lines
2.0 KiB
Markdown

# 配置管理
MengStack 使用 [Viper](https://github.com/spf13/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`**:提供配置模板,方便新人上手