package zhub import ( "fmt" "os" "github.com/spf13/viper" ) // Config zhub客户端配置 type Config struct { Appname string `mapstructure:"appname"` Addr string `mapstructure:"addr"` Groupid string `mapstructure:"groupid"` Auth string `mapstructure:"auth"` } // ConfigOptions 配置加载选项 type ConfigOptions struct { ConfigPath string // 配置文件路径 ConfigName string // 配置文件名 (默认: "app") ConfigType string // 配置文件类型 (默认: "yml") ConfigKey string // 配置节点名 (默认: "zhub") EnvPrefix string // 环境变量前缀 (可选) } // LoadConfigWithOptions 使用选项加载配置 func LoadConfigWithOptions(opts *ConfigOptions) (*Config, error) { viper.Reset() // 设置默认值 if opts.ConfigName == "" { opts.ConfigName = "app" } if opts.ConfigType == "" { opts.ConfigType = "yml" } if opts.ConfigKey == "" { opts.ConfigKey = "zhub" } // 如果指定了配置文件路径,使用指定路径 if opts.ConfigPath != "" { viper.SetConfigFile(opts.ConfigPath) } else { // 否则使用默认搜索路径 viper.SetConfigName(opts.ConfigName) viper.SetConfigType(opts.ConfigType) // 添加多个搜索路径 viper.AddConfigPath(".") viper.AddConfigPath("./conf") viper.AddConfigPath("./config") viper.AddConfigPath("/etc") } // 设置环境变量前缀 if opts.EnvPrefix != "" { viper.SetEnvPrefix(opts.EnvPrefix) viper.AutomaticEnv() } // 读取配置文件 if err := viper.ReadInConfig(); err != nil { return nil, fmt.Errorf("failed to read config file: %w", err) } var config Config if err := viper.UnmarshalKey(opts.ConfigKey, &config); err != nil { return nil, fmt.Errorf("failed to unmarshal config: %w", err) } return &config, nil } // LoadConfig 默认配置加载(向后兼容) func LoadConfig(configPath string) (*Config, error) { opts := &ConfigOptions{ ConfigPath: configPath, ConfigKey: "zhub", } return LoadConfigWithOptions(opts) } // LoadConfigFromProject 从项目配置文件加载(推荐方式) func LoadConfigFromProject(projectConfigPath string) (*Config, error) { // 检查文件是否存在 if _, err := os.Stat(projectConfigPath); os.IsNotExist(err) { return nil, fmt.Errorf("config file not found: %s", projectConfigPath) } opts := &ConfigOptions{ ConfigPath: projectConfigPath, ConfigKey: "zhub", } return LoadConfigWithOptions(opts) }