Anyflag is an implementation of Cobra pflag.Value
and pflag.SliceValue
interfaces using Go Generics.
To bind your custom type to a flag, all you have to do is specify the value type and parser function, and you are done, no boilerplate.
It supports any type including, but not limited to: enums, maps, slices, structs, struct pointers.
It also supports defining custom String() functions to redact passwords, see redact example.
go get github.com/mmatczuk/anyflag
This example shows how anytype
can be used for JSON encoded maps.
func parseJSONMap(val string) (map[string]interface{}, error) {
var m map[string]interface{}
return m, json.Unmarshal([]byte(val), &m)
}
func newCommand() *cobra.Command {
var m map[string]interface{}
cmd := &cobra.Command{
Use: "json-map",
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintln(cmd.OutOrStdout(), m)
},
}
fs := cmd.Flags()
value := anyflag.NewValue[map[string]interface{}](nil, &m, parseJSONMap)
fs.VarP(value, "map", "", "map")
return cmd
}
func main() {
newCommand().Execute()
}
More examples can be found in examples directory.
This project is based on spf13/pflag licensed under the BSD 3-Clause "New" or "Revised" License