github.com/chain5j/chain5j-pkg@v1.0.7/cli/config.go (about) 1 // Package cli cli命令 2 // 3 // @author: xwc1125 4 // @date: 2020/10/11 5 package cli 6 7 import ( 8 "path/filepath" 9 "sync" 10 11 "github.com/fsnotify/fsnotify" 12 "github.com/spf13/viper" 13 ) 14 15 // AppInfo 应用信息 16 type AppInfo struct { 17 App string `json:"app"` 18 Version string `json:"version"` 19 Welcome string `json:"welcome"` 20 } 21 22 var ( 23 eventMapLock sync.Mutex 24 eventMap = make(map[string][]func(e fsnotify.Event), 0) 25 ) 26 27 // LoadConfig 加载本地配置文件 28 func LoadConfig(configFile string, key string, result interface{}) error { 29 viper := viper.New() 30 // 初始化配置文件 31 if configFile != "" { 32 viper.SetConfigFile(configFile) 33 } else { 34 viper.SetConfigName("config") 35 // 添加读取的配置文件路径 36 viper.AddConfigPath(".") 37 viper.AddConfigPath("./conf") 38 } 39 viper.AutomaticEnv() 40 41 if err := viper.ReadInConfig(); err != nil { 42 return err 43 } 44 if len(key) == 0 { 45 if err := viper.Unmarshal(&result); err != nil { 46 return err 47 } 48 } else { 49 if err := viper.UnmarshalKey(key, &result); err != nil { 50 return err 51 } 52 } 53 54 return nil 55 } 56 func LoadConfigWithEvent(configFile string, key string, result interface{}, event func(e fsnotify.Event)) (err error) { 57 // 初始化配置文件 58 if configFile != "" { 59 configFile, err = filepath.Abs(configFile) 60 if err != nil { 61 return err 62 } 63 viper.SetConfigFile(configFile) 64 } else { 65 viper.SetConfigName("config") 66 // 添加读取的配置文件路径 67 viper.AddConfigPath(".") 68 viper.AddConfigPath("./conf") 69 } 70 viper.AutomaticEnv() 71 72 if err := viper.ReadInConfig(); err != nil { 73 return err 74 } 75 if len(key) == 0 { 76 if err := viper.Unmarshal(&result); err != nil { 77 return err 78 } 79 } else { 80 if err := viper.UnmarshalKey(key, &result); err != nil { 81 return err 82 } 83 } 84 eventMapLock.Lock() 85 configFile = filepath.Clean(configFile) 86 if _, ok := eventMap[configFile]; !ok { 87 viper.WatchConfig() 88 } 89 eventMapLock.Unlock() 90 if event != nil { 91 eventMapLock.Lock() 92 if e, ok := eventMap[configFile]; ok { 93 e = append(e, event) 94 eventMap[configFile] = e 95 } else { 96 eventMap[configFile] = append(eventMap[configFile], event) 97 } 98 eventMapLock.Unlock() 99 } 100 viper.OnConfigChange(func(e fsnotify.Event) { 101 eventMapLock.Lock() 102 if events, ok := eventMap[e.Name]; ok { 103 for _, f := range events { 104 f(e) 105 } 106 } 107 eventMapLock.Unlock() 108 }) 109 110 return nil 111 }