package utils import ( "os" "github.com/spf13/viper" ) type Config struct { Server struct { Port string `yaml:"port"` Mode string `yaml:"mode"` } `yaml:"server"` Database DatabaseConfig `yaml:"database"` JWT JWTConfig `yaml:"jwt"` Email EmailConfig `yaml:"email"` Upload UploadConfig `yaml:"upload"` Site SiteConfig `yaml:"site"` Security SecurityConfig `yaml:"security"` } type DatabaseConfig struct { Path string } type JWTConfig struct { Secret string Expire string } type EmailConfig struct { Host string Port int Username string Password string } type UploadConfig struct { Path string } type SiteConfig struct { Title string Description string BaseURL string Logo string Favicon string Copyright string ICP string } type SecurityConfig struct { EncryptKey string } func LoadConfig() (*Config, error) { viper.SetConfigName("config") viper.SetConfigType("yaml") viper.AddConfigPath("./config") // 读取环境变量 viper.AutomaticEnv() if err := viper.ReadInConfig(); err != nil { return nil, err } config := &Config{} if err := viper.Unmarshal(config); err != nil { return nil, err } // 环境变量优先 if port := os.Getenv("SERVER_PORT"); port != "" { config.Server.Port = port } return config, nil }