Add env flag to load .env file.

This commit is contained in:
Arijit Das
2022-01-13 23:15:20 +05:30
parent 143d79fdfc
commit 316bf0990a
2 changed files with 26 additions and 20 deletions
+26 -13
View File
@@ -32,6 +32,7 @@ import (
var (
cfgFile string
envFile string
subCommand string
logWithCommand log.Entry
)
@@ -102,6 +103,7 @@ func init() {
viper.AutomaticEnv()
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file location")
rootCmd.PersistentFlags().StringVar(&envFile, "env", "", "environment file location")
rootCmd.PersistentFlags().String("client-ipcPath", "", "location of geth.ipc file")
rootCmd.PersistentFlags().String("log-level", log.InfoLevel.String(), "log level (trace, debug, info, warn, error, fatal, panic)")
@@ -124,21 +126,32 @@ func init() {
}
func initConfig() {
if cfgFile == "" {
log.Warn("No config file passed with --config flag")
return
if cfgFile == "" && envFile == "" {
log.Fatal("No configuration file specified, use --config , --env flag to provide configuration")
}
viper.SetConfigFile(cfgFile)
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Couldn't read config file: %s", err.Error())
}
log.Infof("Using config file: %s", viper.ConfigFileUsed())
if filepath.Ext(cfgFile) == ".env" {
if err := godotenv.Load(cfgFile); err != nil {
log.Fatalf("Failed to set environment variable from config file: %s", err.Error())
if cfgFile != "" {
if filepath.Ext(cfgFile) != ".toml" {
log.Fatal("Provide .toml file for --config flag")
}
viper.SetConfigFile(cfgFile)
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Couldn't read config file: %s", err.Error())
}
log.Infof("Using config file: %s", viper.ConfigFileUsed())
}
if envFile != "" {
if filepath.Ext(envFile) != ".env" {
log.Fatal("Provide .env file for --env flag")
}
if err := godotenv.Load(envFile); err != nil {
log.Fatalf("Failed to set environment variable from env file: %s", err.Error())
}
log.Infof("Using env file: %s", envFile)
}
}