新增 Config.JWT / JWTConfig(secret、access_token_ttl),ApplyEnvOverrides 支持 JWT_SECRET 与 JWT_ACCESS_TOKEN_TTL 覆盖 YAML。 Access Token 有效期从硬编码 15 分钟改为可配置,默认值 DefaultAccessTokenTTL 与原行为一致,旧配置文件升级后行为不变。applyDefaults 刻意不为 secret 提供默认值:任何硬编码默认密钥都等于公开密钥。 同时消除 D5——JWT_SECRET 原本是全项目唯一绕过 config 层、直接 os.Getenv 的配置项,而 fail-fast 需要一个地方拿到完整配置。
225 lines
5.7 KiB
Go
225 lines
5.7 KiB
Go
package config
|
||
|
||
import (
|
||
"errors"
|
||
"fmt"
|
||
"log"
|
||
"os"
|
||
"strconv"
|
||
"time"
|
||
|
||
"gopkg.in/yaml.v3"
|
||
)
|
||
|
||
type Config struct {
|
||
Server ServerConfig `yaml:"server"`
|
||
Database DatabaseConfig `yaml:"database"`
|
||
Redis RedisConfig `yaml:"redis"`
|
||
RabbitMQ RabbitMQConfig `yaml:"rabbitmq"`
|
||
JWT JWTConfig `yaml:"jwt"`
|
||
ObservabilityConfig ObservabilityConfig `yaml:"observability"`
|
||
}
|
||
|
||
type ServerConfig struct {
|
||
Port int `yaml:"port"`
|
||
}
|
||
|
||
type DatabaseConfig struct {
|
||
Host string `yaml:"host"`
|
||
Port int `yaml:"port"`
|
||
User string `yaml:"user"`
|
||
Password string `yaml:"password"`
|
||
DBName string `yaml:"dbname"`
|
||
}
|
||
|
||
type RedisConfig struct {
|
||
Host string `yaml:"host"`
|
||
Port int `yaml:"port"`
|
||
Password string `yaml:"password"`
|
||
DB int `yaml:"db"`
|
||
}
|
||
|
||
type RabbitMQConfig struct {
|
||
Host string `yaml:"host"`
|
||
Port int `yaml:"port"`
|
||
Username string `yaml:"username"`
|
||
Password string `yaml:"password"`
|
||
}
|
||
|
||
// JWTConfig 承载 JWT 签名与令牌有效期配置。
|
||
// 约定:secret 只通过环境变量 JWT_SECRET 提供,不写入受版本控制的 YAML。
|
||
type JWTConfig struct {
|
||
Secret string `yaml:"secret"`
|
||
// AccessTokenTTL 支持 YAML 的时长字符串写法("15m"/"1h"/"30s")。
|
||
// 注意:yaml.v3 只接受这种字符串形式,写成纯数字(纳秒)会报
|
||
// "cannot unmarshal !!int into time.Duration",因此无需自定义 UnmarshalYAML。
|
||
AccessTokenTTL time.Duration `yaml:"access_token_ttl"`
|
||
}
|
||
|
||
// DefaultAccessTokenTTL 与改动前的硬编码值一致,
|
||
// 保证已有配置文件(尚无 jwt 段)升级后行为不变。
|
||
const DefaultAccessTokenTTL = 15 * time.Minute
|
||
|
||
type ObservabilityConfig struct {
|
||
Pprof PprofConfig `yaml:"pprof"`
|
||
}
|
||
type PprofConfig struct {
|
||
Enabled bool `yaml:"enabled"`
|
||
ApiAddr string `yaml:"api_addr"`
|
||
WorkerAddr string `yaml:"worker_addr"`
|
||
}
|
||
|
||
func Load(filename string) (Config, error) {
|
||
data, err := os.ReadFile(filename)
|
||
if err != nil {
|
||
return Config{}, fmt.Errorf("failed to read config file: %w", err)
|
||
}
|
||
|
||
var cfg Config
|
||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||
return Config{}, fmt.Errorf("parse config %s: %w", filename, err)
|
||
}
|
||
|
||
ApplyEnvOverrides(&cfg)
|
||
applyDefaults(&cfg)
|
||
return cfg, nil
|
||
}
|
||
|
||
func ApplyEnvOverrides(cfg *Config) {
|
||
if cfg == nil {
|
||
return
|
||
}
|
||
if v := os.Getenv("SERVER_PORT"); v != "" {
|
||
if port, err := strconv.Atoi(v); err == nil {
|
||
cfg.Server.Port = port
|
||
}
|
||
}
|
||
if v := os.Getenv("MYSQL_HOST"); v != "" {
|
||
cfg.Database.Host = v
|
||
}
|
||
if v := os.Getenv("MYSQL_PORT"); v != "" {
|
||
if port, err := strconv.Atoi(v); err == nil {
|
||
cfg.Database.Port = port
|
||
}
|
||
}
|
||
if v := os.Getenv("MYSQL_USER"); v != "" {
|
||
cfg.Database.User = v
|
||
}
|
||
if v := os.Getenv("MYSQL_ROOT_PASSWORD"); v != "" {
|
||
cfg.Database.Password = v
|
||
}
|
||
if v := os.Getenv("MYSQL_PASSWORD"); v != "" {
|
||
cfg.Database.Password = v
|
||
}
|
||
if v := os.Getenv("MYSQL_DATABASE"); v != "" {
|
||
cfg.Database.DBName = v
|
||
}
|
||
if v := os.Getenv("REDIS_HOST"); v != "" {
|
||
cfg.Redis.Host = v
|
||
}
|
||
if v := os.Getenv("REDIS_PORT"); v != "" {
|
||
if port, err := strconv.Atoi(v); err == nil {
|
||
cfg.Redis.Port = port
|
||
}
|
||
}
|
||
if v := os.Getenv("REDIS_PASSWORD"); v != "" {
|
||
cfg.Redis.Password = v
|
||
}
|
||
if v := os.Getenv("REDIS_DB"); v != "" {
|
||
if db, err := strconv.Atoi(v); err == nil {
|
||
cfg.Redis.DB = db
|
||
}
|
||
}
|
||
if v := os.Getenv("RABBITMQ_HOST"); v != "" {
|
||
cfg.RabbitMQ.Host = v
|
||
}
|
||
if v := os.Getenv("RABBITMQ_PORT"); v != "" {
|
||
if port, err := strconv.Atoi(v); err == nil {
|
||
cfg.RabbitMQ.Port = port
|
||
}
|
||
}
|
||
if v := os.Getenv("RABBITMQ_USER"); v != "" {
|
||
cfg.RabbitMQ.Username = v
|
||
}
|
||
if v := os.Getenv("RABBITMQ_PASS"); v != "" {
|
||
cfg.RabbitMQ.Password = v
|
||
}
|
||
if v := os.Getenv("JWT_SECRET"); v != "" {
|
||
cfg.JWT.Secret = v
|
||
}
|
||
if v := os.Getenv("JWT_ACCESS_TOKEN_TTL"); v != "" {
|
||
if d, err := time.ParseDuration(v); err == nil {
|
||
cfg.JWT.AccessTokenTTL = d
|
||
} else {
|
||
// 注意:JWT_ACCESS_TOKEN_TTL=30(缺单位)会解析失败。
|
||
// 此处保留原值并告警,不会静默解释成 30 纳秒。
|
||
log.Printf("WARN: invalid JWT_ACCESS_TOKEN_TTL %q: %v (keep %v)", v, err, cfg.JWT.AccessTokenTTL)
|
||
}
|
||
}
|
||
}
|
||
|
||
// applyDefaults 只在缺省时兜底,已显式配置的值一律不覆盖。
|
||
// 注意:这里刻意不为 JWT.Secret 提供默认值——任何硬编码默认密钥都等于公开密钥,
|
||
// 宁可让 auth.Configure 在启动期报错。
|
||
func applyDefaults(cfg *Config) {
|
||
if cfg == nil {
|
||
return
|
||
}
|
||
if cfg.JWT.AccessTokenTTL <= 0 {
|
||
cfg.JWT.AccessTokenTTL = DefaultAccessTokenTTL
|
||
}
|
||
}
|
||
|
||
// bool用来表示是否使用了默认配置,true表示使用了默认配置
|
||
func LoadLocalDev(filename string) (Config, bool, error) {
|
||
cfg, err := Load(filename)
|
||
if err == nil {
|
||
return cfg, false, nil
|
||
}
|
||
if errors.Is(err, os.ErrNotExist) {
|
||
return DefaultLocalConfig(), true, nil
|
||
}
|
||
return Config{}, false, err
|
||
}
|
||
|
||
func DefaultLocalConfig() Config {
|
||
cfg := Config{
|
||
Server: ServerConfig{
|
||
Port: 8080,
|
||
},
|
||
Database: DatabaseConfig{
|
||
Host: "localhost",
|
||
Port: 3306,
|
||
User: "root",
|
||
Password: "123456",
|
||
DBName: "feedsystem",
|
||
},
|
||
Redis: RedisConfig{
|
||
Host: "localhost",
|
||
Port: 6379,
|
||
Password: "123456",
|
||
DB: 0,
|
||
},
|
||
RabbitMQ: RabbitMQConfig{
|
||
Host: "localhost",
|
||
Port: 5672,
|
||
Username: "admin",
|
||
Password: "password123",
|
||
},
|
||
JWT: JWTConfig{
|
||
// 刻意不填 Secret:默认密钥等于公开密钥,交给 auth.Configure 在启动期拒绝。
|
||
AccessTokenTTL: DefaultAccessTokenTTL,
|
||
},
|
||
ObservabilityConfig: ObservabilityConfig{
|
||
Pprof: PprofConfig{
|
||
Enabled: true,
|
||
ApiAddr: "localhost:6060",
|
||
WorkerAddr: "localhost:6061",
|
||
},
|
||
},
|
||
}
|
||
ApplyEnvOverrides(&cfg)
|
||
applyDefaults(&cfg)
|
||
return cfg
|
||
}
|