12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package config
- import (
- "fmt"
- "github.com/fsnotify/fsnotify"
- "github.com/spf13/viper"
- )
- var Conf = new(AppConfig)
- type AppConfig struct {
- Mode string `mapstructure:"mode"`
- Port int `mapstructure:"port"`
- CacheDir string `mapstructure:"cache_dir"`
- *Encrypt `mapstructure:"encrypt"`
- *LogConfig `mapstructure:"log"`
- *MySQLConfig `mapstructure:"mysql"`
- *RedisConfig `mapstructure:"redis"`
- }
- type Encrypt struct {
- Key string `mapstructure:"key"`
- ExpireAt int64 `mapstructure:"expire_at"`
- }
- type LogConfig struct {
- Level string `mapstructure:"level"`
- WebLogName string `mapstructure:"web_log_name"`
- LogFilePath string `mapstructure:"log_file_path"`
- }
- type MySQLConfig struct {
- Host string `mapstructure:"host"`
- User string `mapstructure:"user"`
- Password string `mapstructure:"password"`
- DB string `mapstructure:"dbname"`
- Port int `mapstructure:"port"`
- MaxOpenConns int `mapstructure:"max_open_conns"`
- MaxIdleConns int `mapstructure:"max_idle_conns"`
- }
- type RedisConfig struct {
- Host string `mapstructure:"host"`
- Password string `mapstructure:"password"`
- Port int `mapstructure:"port"`
- DB int `mapstructure:"db"`
- PoolSize int `mapstructure:"pool_size"`
- MinIdleConns int `mapstructure:"min_idle_conns"`
- }
- var (
- devFilePath = "./config/config.dev.yaml"
- releaseFilePath = "./config/config.online.yaml"
- localFilePath = "./config/config.local.yaml"
- )
- func Init(mode string) {
- var filePath string
- if mode == "dev" {
- filePath = devFilePath
- } else if mode == "release" {
- filePath = releaseFilePath
- } else {
- filePath = localFilePath
- }
- viper.SetConfigFile(filePath)
- err := viper.ReadInConfig()
- if err != nil {
-
- panic(fmt.Sprintf("viper.ReadInConfig failed, err:%v\n", err))
- }
-
- if err := viper.Unmarshal(Conf); err != nil {
- fmt.Printf("viper.Unmarshal failed, err:%v\n", err)
- }
- viper.WatchConfig()
- viper.OnConfigChange(func(in fsnotify.Event) {
- fmt.Println("配置文件修改了...")
- if err := viper.Unmarshal(Conf); err != nil {
- panic(fmt.Sprintf("viper.Unmarshal failed, err:%v\n", err))
- }
- })
- }
|