settings.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/fsnotify/fsnotify"
  5. "github.com/spf13/viper"
  6. )
  7. var Conf = new(AppConfig)
  8. type AppConfig struct {
  9. Mode string `mapstructure:"mode"`
  10. Port int `mapstructure:"port"`
  11. CacheDir string `mapstructure:"cache_dir"`
  12. *Encrypt `mapstructure:"encrypt"`
  13. *LogConfig `mapstructure:"log"`
  14. *MySQLConfig `mapstructure:"mysql"`
  15. *RedisConfig `mapstructure:"redis"`
  16. }
  17. type Encrypt struct {
  18. Key string `mapstructure:"key"`
  19. ExpireAt int64 `mapstructure:"expire_at"`
  20. }
  21. type LogConfig struct {
  22. Level string `mapstructure:"level"`
  23. WebLogName string `mapstructure:"web_log_name"`
  24. LogFilePath string `mapstructure:"log_file_path"`
  25. }
  26. type MySQLConfig struct {
  27. Host string `mapstructure:"host"`
  28. User string `mapstructure:"user"`
  29. Password string `mapstructure:"password"`
  30. DB string `mapstructure:"dbname"`
  31. Port int `mapstructure:"port"`
  32. MaxOpenConns int `mapstructure:"max_open_conns"`
  33. MaxIdleConns int `mapstructure:"max_idle_conns"`
  34. }
  35. type RedisConfig struct {
  36. Host string `mapstructure:"host"`
  37. Password string `mapstructure:"password"`
  38. Port int `mapstructure:"port"`
  39. DB int `mapstructure:"db"`
  40. PoolSize int `mapstructure:"pool_size"`
  41. MinIdleConns int `mapstructure:"min_idle_conns"`
  42. }
  43. var (
  44. devFilePath = "./config/config.dev.yaml"
  45. releaseFilePath = "./config/config.online.yaml"
  46. localFilePath = "./config/config.local.yaml"
  47. )
  48. func Init(mode string) {
  49. var filePath string
  50. if mode == "dev" {
  51. filePath = devFilePath
  52. } else if mode == "release" {
  53. filePath = releaseFilePath
  54. } else { // local
  55. filePath = localFilePath
  56. }
  57. viper.SetConfigFile(filePath)
  58. err := viper.ReadInConfig() // 读取配置信息
  59. if err != nil {
  60. // 读取配置信息失败
  61. panic(fmt.Sprintf("viper.ReadInConfig failed, err:%v\n", err))
  62. }
  63. // 把读取到的配置信息反序列化到 Conf 变量中
  64. if err := viper.Unmarshal(Conf); err != nil {
  65. fmt.Printf("viper.Unmarshal failed, err:%v\n", err)
  66. }
  67. viper.WatchConfig()
  68. viper.OnConfigChange(func(in fsnotify.Event) {
  69. fmt.Println("配置文件修改了...")
  70. if err := viper.Unmarshal(Conf); err != nil {
  71. panic(fmt.Sprintf("viper.Unmarshal failed, err:%v\n", err))
  72. }
  73. })
  74. }