package config import ( "fmt" "github.com/spf13/viper" ) type Config struct { App AppConfig `mapstructure:"app"` HTTP HTTPConfig `mapstructure:"http"` } type AppConfig struct { Name string `mapstructure:"name"` Env string `mapstructure:"env"` } type HTTPConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` } func Load(path string) (*Config, error) { v := viper.New() // 指定文件,按 .toml 扩展名识别格式 v.SetConfigFile(path) if err := v.ReadInConfig(); err != nil { return nil, fmt.Errorf("读取配置失败: %w", err) } var cfg Config if err := v.Unmarshal(&cfg); err != nil { return nil, fmt.Errorf("解析配置失败: %w", err) } return &cfg, nil }