Created
January 25, 2023 20:10
-
-
Save oogali/8c3ee4ef8e2c62956e9e51c9e349ba45 to your computer and use it in GitHub Desktop.
Snippet of Cobra and Viper tag-team
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func init() { | |
cobra.OnInitialize(initConfig) | |
viper.SetEnvPrefix("VOYAGER") | |
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) | |
viper.AutomaticEnv() | |
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.voyager.yaml)") | |
rootCmd.PersistentFlags().BoolP("debug", "d", false, "Enable debug logging") | |
viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) | |
viper.BindEnv("debug", "DEBUG") | |
rootCmd.PersistentFlags().StringP("database-url", "", "", "Database URL") | |
viper.BindPFlag("database-url", rootCmd.PersistentFlags().Lookup("database-url")) | |
viper.BindEnv("database-url", "DATABASE_URL") | |
} | |
func initConfig() { | |
if cfgFile != "" { | |
// Use config file from the flag. | |
viper.SetConfigFile(cfgFile) | |
} else { | |
// Find home directory. | |
home, err := os.UserHomeDir() | |
if err != nil { | |
log.Fatal().Err(err).Msg("could not get home directory") | |
} | |
// Search config in home directory with name ".cobra" (without extension). | |
viper.AddConfigPath(home) | |
viper.SetConfigType("yaml") | |
viper.SetConfigName(".voyager") | |
} | |
viper.AutomaticEnv() | |
logLevel := zerolog.InfoLevel | |
if viper.GetBool("debug") { | |
logLevel = zerolog.DebugLevel | |
} | |
zerolog.SetGlobalLevel(logLevel) | |
if err := viper.ReadInConfig(); err != nil { | |
if _, ok := err.(viper.ConfigFileNotFoundError); !ok { | |
log.Fatal().Err(err).Msg("could not read configuration file") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment