package conf import ( "fmt" "github.com/spf13/viper" "os" ) var cfg = Config{} type Config struct { Database Database `mapstructure:"database"` // 数据库配置 } type Database struct { Host string `mapstructure:"host"` User string `mapstructure:"user"` Dbname string `mapstructure:"dbname"` Pwd string `mapstructure:"pwd"` } func LoadConfig() { path, err := os.Getwd() if err != nil { panic(err) } viper.AddConfigPath(path + "/conf") viper.SetConfigName("config") viper.SetConfigType("yaml") if err := viper.ReadInConfig(); err != nil { fmt.Println("读取配置文件失败, 异常信息: ", err) panic(err) } // 将文件内容解析后封装到cfg对象中 if err := viper.Unmarshal(&cfg); err != nil { fmt.Println("解析配置文件失败, 异常信息 : ", err) } } // GetInfo 获取配置文件 func GetInfo() Config { return cfg }