Merge pull request #27 from owncloud/feature/config

Load config from Viper on Before hook
This commit is contained in:
Alex Unger
2020-03-18 18:53:46 +01:00
committed by GitHub
3 changed files with 50 additions and 40 deletions

View File

@@ -0,0 +1,5 @@
Enhancement: Configuration
Extensions should be responsible of configuring themselves. We use Viper for config loading from default paths. Environment variables **WILL** take precedence over config files.
https://github.com/owncloud/ocis-graph/pull/27

View File

@@ -32,45 +32,7 @@ func Execute() error {
Flags: flagset.RootWithConfig(cfg),
Before: func(c *cli.Context) error {
logger := NewLogger(cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("GRAPH")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("graph")
viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Info().
Msg("Continue without config")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}
return nil
return ParseConfig(c, cfg)
},
Commands: []*cli.Command{
@@ -101,3 +63,46 @@ func NewLogger(cfg *config.Config) log.Logger {
log.Color(cfg.Log.Color),
)
}
// ParseConfig reads graph configuration from fs.
func ParseConfig(c *cli.Context, cfg *config.Config) error {
logger := NewLogger(cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("GRAPH")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("graph")
viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Info().
Msg("Continue without config")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}
return nil
}

View File

@@ -34,7 +34,7 @@ func Server(cfg *config.Config) *cli.Command {
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
}
return nil
return ParseConfig(c, cfg)
},
Action: func(c *cli.Context) error {
logger := NewLogger(cfg)