Created
November 23, 2016 21:38
-
-
Save thorduri/cd90608685352c0b619a05d0c8941451 to your computer and use it in GitHub Desktop.
viper.ConfigPaths()
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
package main | |
import ( | |
"fmt" | |
"os" | |
log "github.com/Sirupsen/logrus" | |
"github.com/spf13/cobra" | |
"github.com/spf13/viper" | |
) | |
func main() { | |
rootCmd := &cobra.Command{ | |
Use: "test", | |
PersistentPreRun: func(cmd *cobra.Command, args []string) { | |
if viper.GetBool("debug") { | |
log.SetLevel(log.DebugLevel) | |
} | |
}, | |
PreRunE: func(cmd *cobra.Command, args []string) (err error) { | |
config := viper.GetString("config") | |
if config != "" { | |
viper.SetConfigFile(config) | |
} | |
if err = viper.ReadInConfig(); err != nil { | |
if _, ok := err.(viper.ConfigFileNotFoundError); !ok { | |
return err | |
} | |
if config != "" { | |
return err | |
} | |
} | |
configUsed := viper.ConfigFileUsed() | |
clog := log.WithFields(log.Fields{ | |
"config": configUsed, | |
"locations": viper.ConfigPaths(), | |
}) | |
if configUsed == "" { | |
clog.Warn("preflight complete") | |
} else { | |
clog.Info("preflight complete") | |
} | |
return nil | |
}, | |
Run: func(cmd *cobra.Command, args []string) { | |
fmt.Printf("run!\n") | |
}, | |
} | |
rootCmd.PersistentFlags().StringP("config", "c", "", "config file") | |
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config")) | |
rootCmd.PersistentFlags().BoolP("debug", "d", false, "debug output") | |
viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) | |
viper.SetConfigName("config") | |
viper.AddConfigPath(".") | |
viper.AddConfigPath("etc/") | |
viper.AutomaticEnv() | |
if err := rootCmd.Execute(); err != nil { | |
fmt.Printf("oops: %v\n", err) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment