config.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package util
  2. import (
  3. "strings"
  4. "github.com/spf13/viper"
  5. "github.com/chrislusf/seaweedfs/weed/util/log"
  6. )
  7. type Configuration interface {
  8. GetString(key string) string
  9. GetBool(key string) bool
  10. GetInt(key string) int
  11. GetStringSlice(key string) []string
  12. SetDefault(key string, value interface{})
  13. }
  14. func LoadConfiguration(configFileName string, required bool) (loaded bool) {
  15. // find a filer store
  16. viper.SetConfigName(configFileName) // name of config file (without extension)
  17. viper.AddConfigPath(".") // optionally look for config in the working directory
  18. viper.AddConfigPath("$HOME/.seaweedfs") // call multiple times to add many search paths
  19. viper.AddConfigPath("/etc/seaweedfs/") // path to look for the config file in
  20. log.Debugf("Reading %s.toml from %s", configFileName, viper.ConfigFileUsed())
  21. if err := viper.MergeInConfig(); err != nil { // Handle errors reading the config file
  22. if strings.Contains(err.Error(), "Not Found") {
  23. log.Warnf("Reading %s: %v", viper.ConfigFileUsed(), err)
  24. } else {
  25. log.Infof("Reading %s: %v", viper.ConfigFileUsed(), err)
  26. }
  27. if required {
  28. log.Fatalf("Failed to load %s.toml file from current directory, or $HOME/.seaweedfs/, or /etc/seaweedfs/"+
  29. "\n\nPlease use this command to generate the default %s.toml file\n"+
  30. " weed scaffold -config=%s -output=.\n\n\n",
  31. configFileName, configFileName, configFileName)
  32. } else {
  33. return false
  34. }
  35. }
  36. return true
  37. }
  38. func GetViper() *viper.Viper {
  39. v := &viper.Viper{}
  40. *v = *viper.GetViper()
  41. v.AutomaticEnv()
  42. v.SetEnvPrefix("weed")
  43. v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
  44. return v
  45. }