IssueRaiser

Add capability to restrict flag values to a set of allowed values

I have a use-case where I need to perform validation on flag values. In other words, I need to check that the value passed in by the user belongs to some set of valid values. I end up writing a lot of code that looks like this: ``` package main import ( "fmt" "os" flag "github.com/spf13/pflag" ) var color string func main() { addFlags() flag.Parse() if err := validateFlags(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v", err) os.Exit(1) } fmt.Printf("Selected color is %s\n", color) } func addFlags() { flag.StringVar(&color, "color", "", "The color for the example") } func validateFlags() error { validColors := []string{"red", "blue", "yellow"} for _, validColor := range validColors { if color == validColor { // color is valid return nil } } // if we're here, color is invalid return fmt.Errorf("Value '%s' is invalid for flag 'color'. Valid values "+ "come from the set %v", color, validColors) } ``` I'd like to be able to do something like the following: ``` flag.StringVarRestricted( &color, // pointer to variable "color", // flag name "", // default value "The color for the example", // description []string{"red", "blue", "yellow"}) // Allowed values ``` I wouldn't mind taking a shot at implementing something like this if it sounds acceptable.

Posted by ian-howell on Jan 23, 2020, 3:34 PM

Tags

Related issues

Raise real-world problems, find people facing the same issue, and discuss solutions.3,500 issues0 comments

github (Software)

Add capability to restrict flag values to a set of allowed values

ian-howellJan 23, 2020, 3:34 PM

I have a use-case where I need to perform validation on flag values. In other words, I need to check that the value passed in by the user belongs to some set of valid values. I end up writing a lot of code that looks like this: ``` package main import ( "fmt" "os" flag "github.com/spf13/pflag" ) var color string func main() { addFlags() flag.Parse() if err := validateFlags(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v", err) os.Exit(1) } fmt.Printf("Selected color is %s\n", color) } func addFlags() { flag.StringVar(&color, "color", "", "The color for the example") } func validateFlags() error { validColors := []string{"red", "blue", "yellow"} for _, validColor := range validColors { if color == validColor { // color is valid return nil } } // if we're here, color is invalid return fmt.Errorf("Value '%s' is invalid for flag 'color'. Valid values "+ "come from the set %v", color, validColors) } ``` I'd like to be able to do something like the following: ``` flag.StringVarRestricted( &color, // pointer to variable "color", // flag name "", // default value "The color for the example", // description []string{"red", "blue", "yellow"}) // Allowed values ``` I wouldn't mind taking a shot at implementing something like this if it sounds acceptable.

Comments (0)

No comments yet. Start the discussion.

Comment on this issue