From 20c4f14750f18050f88aceef8adb788342576a25 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Tue, 16 Aug 2022 21:07:10 +0530 Subject: reading config file with viper --- cmd/root.go | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'cmd') diff --git a/cmd/root.go b/cmd/root.go index f1fba18..2c6ca56 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -20,8 +20,10 @@ package cmd import ( "os" + "fmt" "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( @@ -32,7 +34,29 @@ var ( var rootCmd = &cobra.Command{ Use: "macli", Short: "macli - Unofficial CLI-Based MyAnimeList Client.", - Long: "macli is an unofficial MyAnimeClient for use inside the terminal.", + Long: "macli is an unofficial MyAnimeList Client for use inside the terminal.", +} + +func init() { + viper.SetConfigName("macli") + viper.SetConfigType("yaml") + viper.AddConfigPath("$HOME/.config/macli") + viper.AddConfigPath("/etc/macli") + + // dont show error if file not found + // macli doesnt need a config file to work properly + if err := viper.ReadInConfig(); err != nil { + // error if config file found but has errors + if _, ok := err.(viper.ConfigFileNotFoundError); !ok { + fmt.Println("Error while reading macli config file:", err) + os.Exit(1) + } + } + + name := viper.Get("name").(map[string]interface{}) + + fmt.Println("Config File Contents:", name["last"]) + os.Exit(0) } func Execute() { -- cgit v1.2.3