配置说明
配置目录:configs/
configs/
├── dev.yaml # 开发环境配置
├── test.yaml # 测试环境配置
└── prod.yaml # 生产环境配置配置加载
加载优先级
- 环境变量
APP_ENV决定加载哪个配置文件 - 默认加载
dev.yaml
bash
# 开发环境
export APP_ENV=dev
# 生产环境
export APP_ENV=prod
# 启动应用
go run main.go环境变量覆盖
任何配置项都可以通过环境变量覆盖,格式:APP_<模块>_<字段>
bash
# 覆盖数据库密码
export APP_DATABASE_PASSWORD="new-password"
# 覆盖 Redis 地址
export APP_REDIS_HOST="remote-redis.com"
# 覆盖 JWT 密钥
export APP_SECURITY_JWT_SECRETKEY="new-secret"数据库配置
yaml
database:
host: www.youlai.tech # MySQL 主机地址
port: 3306 # MySQL 端口
username: youlai # 数据库用户名
password: 123456 # 数据库密码
dbname: youlai_admin # 数据库名称
charset: utf8mb4 # 字符集
parseTime: true # 自动解析时间类型
loc: Local # 时区设置
# 连接池配置
maxIdleConns: 10 # 最大空闲连接数
maxOpenConns: 100 # 最大打开连接数
connMaxLifetime: 3600 # 连接最大存活时间(秒)| 配置项 | 默认值 | 说明 |
|---|---|---|
host | localhost | MySQL 主机地址 |
port | 3306 | MySQL 端口 |
maxIdleConns | 10 | 最大空闲连接数 |
maxOpenConns | 100 | 最大打开连接数 |
connMaxLifetime | 3600 | 连接最大存活时间(秒) |
Redis 配置
yaml
redis:
host: www.youlai.tech # Redis 主机
port: 6379 # Redis 端口
password: 123456 # Redis 密码
database: 4 # Redis 数据库编号
# 连接池配置
pool:
maxIdle: 10 # 最大空闲连接数
maxActive: 100 # 最大活动连接数
minIdle: 5 # 最小空闲连接数
# 超时配置(秒)
timeout:
dial: 5 # 建立连接超时
read: 3 # 读取超时
write: 3 # 写入超时
pool: 5 # 连接池获取连接超时日志配置
yaml
logger:
level: debug # 日志级别
console:
enabled: true # 是否启用控制台输出
color: true # 是否启用彩色输出
format: text # 输出格式:text/json
file:
enabled: true # 是否启用文件输出
path: logs/dev.log # 日志文件路径
maxSize: 100 # 单文件最大大小(MB)
maxBackups: 7 # 保留旧文件数量
maxAge: 7 # 保留天数
compress: false # 是否压缩旧日志
errorPath: logs/dev-error.log # 错误日志路径安全配置
yaml
security:
sessionType: jwt # 会话类型:jwt/redis-token
# JWT 配置
jwt:
secretKey: "change-me" # JWT 签名密钥
accessTokenTTL: 7200 # 访问令牌有效期(秒)
refreshTokenTTL: 2592000 # 刷新令牌有效期(秒)
enableSecurityVersion: true # 启用安全版本号
# Redis Token 配置
redisToken:
accessTokenTTL: 7200
refreshTokenTTL: 2592000
allowMultiLogin: true # 是否允许多设备登录会话模式
| 模式 | 说明 | 适用场景 |
|---|---|---|
jwt | 无状态,Token 自包含信息 | 微服务、分布式 |
redis-token | 有状态,Token 存储在 Redis | 需要会话治理 |
环境差异
开发环境(dev.yaml)
- 日志级别:
debug - 控制台彩色输出
- 允许多设备登录
生产环境(prod.yaml)
- 日志级别:
info - JSON 格式输出
- 单设备登录
- 更严格的密钥配置
配置读取
go
package config
import "github.com/spf13/viper"
type Config struct {
Database DatabaseConfig `mapstructure:"database"`
Redis RedisConfig `mapstructure:"redis"`
Logger LoggerConfig `mapstructure:"logger"`
Security SecurityConfig `mapstructure:"security"`
}
func Load() (*Config, error) {
v := viper.New()
v.SetConfigName(getEnv("APP_ENV", "dev"))
v.SetConfigType("yaml")
v.AddConfigPath("configs")
// 支持环境变量覆盖
v.AutomaticEnv()
v.SetEnvPrefix("APP")
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
}相关文件
| 文件 | 说明 |
|---|---|
pkg/config/config.go | 配置加载逻辑 |
configs/dev.yaml | 开发环境配置 |
configs/prod.yaml | 生产环境配置 |
configs/test.yaml | 测试环境配置 |
