go get github.com/Gers2017/flago
Import flago
import (
"github.com/Gers2017/flago"
)
Populate the flagset
get := flago.NewFlagSet("get")
get.Bool("all", false)
get.Switch("verbose") // Same as get.Bool("verbose", false)
get := flago.NewFlagSet("get").
Bool("all", false).
Switch("verbose") // Same as get.Bool("verbose", false)
cli := flago.NewCli()
cli.Handle(get, func(fs *flago.FlagSet) error {
HandleFlagset(fs) // do something with parsed get
return nil
})
if err := cli.Execute(os.Args); err != nil {
log.Fatal(err)
}
func HandleFlagset(fs *flago.FlagSet) {
if fs.Bool("help") {
fmt.Println("Some helpful help message")
return
}
// Do something...
fmt.Println(todos)
}
Parse the arguments into flags
// os.Args = []string{ "cli", "all", "help" }
if err := get.ParseFlags(os.Args[1:]); err != nil {
log.Fatal(err)
return
}
Then use the parsed flagset
if get.IsParsed("all") {
if get.Bool("help") {
fmt.Println("Some helpful help message")
return
}
// Do something...
fmt.Println(todos)
}
A complete example can be found here
get := flago.NewFlagSet("get")
get.SetSwitch("verbose")
get.Int("x", 0)
It's highly recommended to use this method to check first if a flag was parsed correctly.
get.IsParsed("your-flag-name")
The FlagSet.[Bool, Int, Float, Str]
methods are just a shortcut for:
verbose := get.Bool("verbose")
x := get.Int("x")
If the flag name inside the getter method is not registered in the flagset, you'll get an error at runtime.
wrong := get.Bool("some-invalid-flag")
-
The
FlagSet.[Bool, Int, Float, Str]
method can raise an error at runtine (useFlagSet.IsParsed
to avoid this) -
A note on golang's generics Behind the scenes flago uses maps + generics + type parsing The
Flag struct
contains aValue
property of typeany
.Because if we try to use generics we'd need to declare a map for every type of flag inside Flagset, and
Flags map[string]*Flag
wouldn't work anymore leading to repeated code.The flag module in the standard library solves this by using pointers to the underliying values.