diff --git a/README.md b/README.md index 08c2e97..5213c2a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1539 TILs and counting..._ +_1540 TILs and counting..._ --- @@ -403,6 +403,7 @@ _1539 TILs and counting..._ - [Access Go Docs Offline](go/access-go-docs-offline.md) - [Add A Method To A Struct](go/add-a-method-to-a-struct.md) - [Build For A Specific OS And Architecture](go/build-for-a-specific-os-and-architecture.md) +- [Check If Cobra Flag Was Set](go/check-if-cobra-flag-was-set.md) - [Combine Two Slices](go/combine-two-slices.md) - [Do Something N Times](go/do-something-n-times.md) - [Find Executables Installed By Go](go/find-executables-installed-by-go.md) diff --git a/go/check-if-cobra-flag-was-set.md b/go/check-if-cobra-flag-was-set.md new file mode 100644 index 0000000..b51039e --- /dev/null +++ b/go/check-if-cobra-flag-was-set.md @@ -0,0 +1,41 @@ +# Check If Cobra Flag Was Set + +When using [Cobra](https://github.com/spf13/cobra) to define a CLI, we can +specify a flag for a command like so: + +```go +var Seed int64 +myCmd.PersistentFlags().Int64VarP(&Seed, "seed", "", -1, "set a seed") +``` + +This `--seed` flag has a _default_ of `-1`. If the flag isn't specified, then +when we access that flag's value, we'll get `-1`. + +But how do we differentiate between the _default_ `-1` and someone passing `-1` +to the `--seed` flag when running the program? + +In the command definition, we can look at the flags and see, by name, if +specific ones were changed by user input rather than being the defaults. + +```go +myCommand := &cobra.Command{ + // coommand setup ... + Run: func(cmd *cobra.Command, args []string) { + if cmd.Flags().Changed("seed") { + seed, err := cmd.Flags().GetInt64("seed") + if err != nil { + fmt.Println("Seed flag is missing from `cmdFlags()`") + os.Exit(1) + } + + fmt.Printf("Seed was set to %d\n", seed) + } else { + fmt.Println("Seed was not set") + } + } +} +``` + +If we don't want to rely on the default and instead want to specify some other +behavior when the flag is not manually set by the user, we can detect that +scenario like this.