Last active
November 8, 2018 01:29
-
-
Save dwburke/597c265b65cbb4d96849be3dcbefddfa to your computer and use it in GitHub Desktop.
cobra/viper root.go template
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 ( | |
"github.com/dwburke/xxxx/cmd" | |
) | |
func main() { | |
cmd.Execute() | |
} |
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 cmd | |
import ( | |
"fmt" | |
"os" | |
homedir "github.com/mitchellh/go-homedir" | |
"github.com/spf13/cobra" | |
"github.com/spf13/viper" | |
) | |
var cfgFile string | |
func init() { | |
cobra.OnInitialize(initConfig) | |
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") | |
} | |
var rootCmd = &cobra.Command{ | |
Use: "dburke-things", | |
Short: "dburke-things is a thing", | |
Long: `Love me`, | |
Run: func(cmd *cobra.Command, args []string) { | |
cmd.Usage() | |
}, | |
} | |
func Execute() { | |
if err := rootCmd.Execute(); err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
} | |
func initConfig() { | |
// Don't forget to read config either from cfgFile or from home directory! | |
if cfgFile != "" { | |
// Use config file from the flag. | |
viper.SetConfigFile(cfgFile) | |
} else { | |
// Find home directory. | |
home, err := homedir.Dir() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
// Search config in home directory with name ".cobra" (without extension). | |
viper.AddConfigPath(home) | |
viper.AddConfigPath("./") | |
viper.SetConfigName(".dburke-things") | |
} | |
if err := viper.ReadInConfig(); err != nil { | |
fmt.Fprintf(os.Stderr, "Unable to load config file, using defaults.\n") | |
//fmt.Println("Can't read config:", err) | |
//os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tweaked version of the cobra example... just have to change references of 'dburke-things' to suit your app, and decide if you want a failure to read the config at the bottom to be fatal or use your defaults (ymmv)