package conf import ( l4g "github.com/alecthomas/log4go" "github.com/spf13/viper" "os" "path" ) var cfg = Config{} type Config struct { Database Database `mapstructure:"database"` // 数据库配置 Report Report `mapstructure:"report"` // 报表 } type Database struct { Host string `mapstructure:"host"` User string `mapstructure:"user"` Dbname string `mapstructure:"dbname"` Pwd string `mapstructure:"pwd"` Port int `mapstructure:"port"` Charset string `mapstructure:"charset"` } type Report struct { Template string `mapstructure:"template"` Out string `mapstructure:"out"` } func LoadConfig(logger *l4g.Logger) { path, err := os.Getwd() if err != nil { panic(err) } viper.AddConfigPath(path) logger.Debug("配置文件路径为 %s", path) viper.SetConfigName("config") viper.SetConfigType("yaml") if err := viper.ReadInConfig(); err != nil { logger.Error("读取配置文件失败, 异常信息: ", err) panic(err) } // 将文件内容解析后封装到cfg对象中 if err := viper.Unmarshal(&cfg); err != nil { logger.Error("解析配置文件失败, 异常信息 : ", err) } } // GetInfo 获取配置文件 func GetInfo() Config { templateFile := cfg.Report.Template if !isExist(templateFile) { cfg.Report.Template = path.Base(templateFile) } return cfg } // 文件是否存在 func isExist(fileAddr string) bool { _, err := os.Stat(fileAddr) if err != nil { if os.IsExist(err) { return true } return false } return true }