package utils import ( "strings" "sync" "gosvc/logger" "github.com/spf13/viper" ) var ( ConfigurationFileDirectory DirectoryValueType loadSecurityConfigOnce sync.Once ) type DirectoryValueType string func (s *DirectoryValueType) Set(value string) error { *s = DirectoryValueType(value) return nil } func (s *DirectoryValueType) String() string { return string(*s) } type Configuration interface { GetString(key string) string GetBool(key string) bool GetInt(key string) int GetStringSlice(key string) []string SetDefault(key string, value interface{}) } func LoadSecurityConfiguration() { loadSecurityConfigOnce.Do(func() { LoadConfiguration("security", false) }) } func LoadConfiguration(configFileName string, required bool) (loaded bool) { viper.SetConfigName(configFileName) // name of config file (without extension) viper.AddConfigPath(".") // look for config in the working directory if err := viper.MergeInConfig(); err != nil { // Handle errors reading the config file if strings.Contains(err.Error(), "Not Found") { logger.Info("Reading %s: %v", viper.ConfigFileUsed(), err) } else { logger.Error("Reading %s: %v", viper.ConfigFileUsed(), err) } if required { logger.Error("Failed to load %s.yaml file from current directory\n"+ "\nPlease use this command to run the program:\n"+ " robotfs --config=%s.yaml\n\n\n", configFileName, configFileName) } return false } logger.Info("Reading %s.yaml from %s", configFileName, viper.ConfigFileUsed()) return true } type ViperProxy struct { *viper.Viper sync.Mutex } var ( vp = &ViperProxy{} ) func (vp *ViperProxy) SetDefault(key string, value interface{}) { vp.Lock() defer vp.Unlock() vp.Viper.SetDefault(key, value) } func (vp *ViperProxy) GetString(key string) string { vp.Lock() defer vp.Unlock() return vp.Viper.GetString(key) } func (vp *ViperProxy) GetBool(key string) bool { vp.Lock() defer vp.Unlock() return vp.Viper.GetBool(key) } func (vp *ViperProxy) GetInt(key string) int { vp.Lock() defer vp.Unlock() return vp.Viper.GetInt(key) } func (vp *ViperProxy) GetStringSlice(key string) []string { vp.Lock() defer vp.Unlock() return vp.Viper.GetStringSlice(key) } func GetViper() *ViperProxy { vp.Lock() defer vp.Unlock() if vp.Viper == nil { vp.Viper = viper.GetViper() vp.AutomaticEnv() vp.SetEnvPrefix("robotfs") vp.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) } return vp }