package config import ( "log" "github.com/spf13/viper" ) type Config struct { Server ServerConfig Database DatabaseConfig JWT JWTConfig License LicenseConfig } type ServerConfig struct { Port string `mapstructure:"port"` Mode string `mapstructure:"mode"` // debug | release } type DatabaseConfig struct { DSN string `mapstructure:"dsn"` } type JWTConfig struct { Secret string `mapstructure:"secret"` AccessExpireMin int `mapstructure:"access_expire_min"` // Access Token 有效分钟数 RefreshExpireH int `mapstructure:"refresh_expire_h"` // Refresh Token 有效小时数 } type LicenseConfig struct { HMACSecret string `mapstructure:"hmac_secret"` // 许可证签名密钥 } var C Config func Load() { viper.SetConfigName("config") viper.SetConfigType("yaml") viper.AddConfigPath(".") viper.AddConfigPath("./config") // 环境变量覆盖(生产部署时使用) viper.AutomaticEnv() // 默认值 viper.SetDefault("server.port", "8080") viper.SetDefault("server.mode", "debug") viper.SetDefault("jwt.access_expire_min", 60) viper.SetDefault("jwt.refresh_expire_h", 168) // 7天 if err := viper.ReadInConfig(); err != nil { log.Println("[config] no config file found, using defaults and env vars") } if err := viper.Unmarshal(&C); err != nil { log.Fatalf("[config] failed to unmarshal config: %v", err) } }