conf.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package conf
  2. import (
  3. l4g "github.com/alecthomas/log4go"
  4. "github.com/spf13/viper"
  5. "os"
  6. "path"
  7. )
  8. var cfg = Config{}
  9. type Config struct {
  10. Database Database `mapstructure:"database"` // 数据库配置
  11. Report Report `mapstructure:"report"` // 报表
  12. }
  13. type Database struct {
  14. Host string `mapstructure:"host"`
  15. User string `mapstructure:"user"`
  16. Dbname string `mapstructure:"dbname"`
  17. Pwd string `mapstructure:"pwd"`
  18. Port int `mapstructure:"port"`
  19. Charset string `mapstructure:"charset"`
  20. }
  21. type Report struct {
  22. Template string `mapstructure:"template"`
  23. Out string `mapstructure:"out"`
  24. }
  25. func LoadConfig(logger *l4g.Logger) {
  26. path, err := os.Getwd()
  27. if err != nil {
  28. panic(err)
  29. }
  30. viper.AddConfigPath(path)
  31. logger.Debug("配置文件路径为 %s", path)
  32. viper.SetConfigName("config")
  33. viper.SetConfigType("yaml")
  34. if err := viper.ReadInConfig(); err != nil {
  35. logger.Error("读取配置文件失败, 异常信息: ", err)
  36. panic(err)
  37. }
  38. // 将文件内容解析后封装到cfg对象中
  39. if err := viper.Unmarshal(&cfg); err != nil {
  40. logger.Error("解析配置文件失败, 异常信息 : ", err)
  41. }
  42. }
  43. // GetInfo 获取配置文件
  44. func GetInfo() Config {
  45. templateFile := cfg.Report.Template
  46. if !isExist(templateFile) {
  47. cfg.Report.Template = path.Base(templateFile)
  48. }
  49. return cfg
  50. }
  51. // 文件是否存在
  52. func isExist(fileAddr string) bool {
  53. _, err := os.Stat(fileAddr)
  54. if err != nil {
  55. if os.IsExist(err) {
  56. return true
  57. }
  58. return false
  59. }
  60. return true
  61. }