package config import "github.com/spf13/viper" type config struct { Viper *viper.Viper } func New() *config { var c config c.Viper = viper.New() c.Viper.SetConfigName(defaultName) //defaultName := lib.AppName() c.Viper.SetConfigType(defaultConfigType) c.Viper.AddConfigPath(defaultPath) return &c } func NewConfig(name, suffix, path string) *config { var c config c.Viper = viper.New() c.Viper.SetConfigName(name) //defaultName := lib.AppName() c.Viper.SetConfigType(suffix) c.Viper.AddConfigPath(path) return &c } func (c *config) Load() error { return c.Viper.ReadInConfig() } func (c *config) Store() error { err := viper.SafeWriteConfig() if err != nil { err = viper.WriteConfig() } return err } func (c *config) Register(module, key string, value any) { c.Viper.SetDefault(module+"."+key, value) } func (c *config) GetBool(module, key string) bool { return c.Viper.GetBool(module + "." + key) } func (c *config) GetString(module, key string) string { return c.Viper.GetString(module + "." + key) } func (c *config) GetInt(module, key string) int { return c.Viper.GetInt(module + "." + key) } func (c *config) GetFloat(module, key string) float64 { return c.Viper.GetFloat64(module + "." + key) } func (c *config) GetStringSlice(module string, key string) []string { return c.Viper.GetStringSlice(module + "." + key) } func (c *config) Set(module, key string, value any) { c.Viper.Set(module+"."+key, value) } func (c *config) Unmarshal(module, key string, value any) error { return c.Viper.UnmarshalKey(module+"."+key, value) } func (c *config) ReadConfigAndFileExist() (bool, error) { if err := c.Viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { // 配置文件未找到 return false, nil } else { // 其他错误 return true, err } } return true, nil }