Super simple package for binding command-line flags to your struct.
go get github.com/KimMachineGun/flagopackage main
import (
"fmt""log""strings""time""github.com/KimMachineGun/flago"
)
typeFlagsstruct {
Astring`flago:"a,usage of a"`Bint`flago:"b,usage of b"`CCommaSeparatedStrings`flago:"c,usage of c"`D time.Time`flago:"d,usage of d"`ENestedFlags`flago:"e.,nested flags: "`
}
typeNestedFlagsstruct {
Astring`flago:"a,usage of a"`Bint`flago:"b,usage of b"`
}
// CommaSeparatedStrings implements flag.Value.typeCommaSeparatedStrings []stringfunc (s*CommaSeparatedStrings) String() string {
returnstrings.Join(*s, ",")
}
func (s*CommaSeparatedStrings) Set(vstring) error {
*s=strings.Split(v, ",")
returnnil
}
// go run main.go -b=360 -c=Hello,World -d=2020-01-02T00:00:00Z -e.a=CDfuncmain() {
// set default valuesflags:=Flags{
A: "AB",
B: 180,
C: []string{"Foo", "Bar"},
D: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
E: NestedFlags{
A: "AB",
B: 180,
},
}
// go run main.go --help// Output:// -a string// usage of a (default "AB")// -b int// usage of b (default 180)// -c value// usage of c (default Foo,Bar)// -d value// usage of d (default 2020-01-01T00:00:00Z)// -e.a string// nested flags: usage of a (default "AB")// -e.b int// nested flags: usage of b (default 180)// parse flagserr:=flago.Parse(&flags)
iferr!=nil {
log.Fatalln(err)
}
fmt.Println(flags)
// Output: {AB 360 [Hello World] 2020-01-02 00:00:00 +0000 UTC {CD 180}}
}