From dc20f95f1fb837ec7771f3f0e209a1222db76f80 Mon Sep 17 00:00:00 2001 From: Miguel Elias dos Santos Date: Tue, 25 Feb 2020 17:46:37 +1100 Subject: [PATCH] Add example regarding required flags with Cobra + Viper --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 45e72f2..ee03780 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,16 @@ os.Setenv("SPF_ID", "13") // typically done outside of the app id := Get("id") // 13 ``` +#### When working with *required flags with Cobra+Viper*, you must set the flag values after binding to them. Otherwise Cobra won't be aware of the value from any source other tha the CLI itself. + +```go +serverCmd.Flags().VisitAll(func(f *pflag.Flag) { + if viper.IsSet(f.Name) && viper.GetString(f.Name) != "" { + serverCmd.Flags().Set(f.Name, viper.GetString(f.Name)) + } +}) +``` + ### Working with Flags Viper has the ability to bind to flags. Specifically, Viper supports `Pflags`