forked from ogier/pflag
-
Notifications
You must be signed in to change notification settings - Fork 367
Open
Milestone
Description
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.
umarcor, XSAM, Lateks, fredbi, aceligowska and 228 more
Metadata
Metadata
Assignees
Labels
No labels