Hi all,
I'd like to announce a small package that provides support for tagging struct fields as a way to declare command line arguments.
The package works by calling functions of the
flag package for each of the tagged fields. With a single function call, you can set up a number of tags with default values and usage descriptions. The flags are created using
flag.*Var functions, such as
flag.IntVar(...), so once the flags are parsed, the tagged struct fields will contain either the user-provided flag value or the default value specified in the tag.
The package has support for nested structs, all primitive types that are supported by '
flag',
time.Duration and it tests whether a field variable implements the
http://golang.org/pkg/flag/#Value interface. '
flagtag' simply uses the facilities provided by the '
flag' package. It is possible to partially use the
flagtag package for simple flags and use the '
flag' package directly for complex requirements.
I believe that the package will be most useful when creating small tools that do not require any special flag behavior. In its simplest form you can create flags by simply tagging the appropriate struct fields, then calling
MustConfigureAndParse(&s) where
s is the variable of the (tagged) struct type. With just a single function to call, setting up the flags is easy. By having tags for the appropriate struct fields, it is very easy to keep an overview of the flags that are available and by which flag names. (Please keep in mind that the Must* functions
will panic if invalid tag data is provided. Use
ConfigureAndParse(&s) if you want an error returned.)
Let me know what you think. I appreciate any feedback, also because this is the first package I am actually announcing. There is probably a lot that can be improved in the code, the documentation or anything else.
Kind regards,
Danny
A simple example:
package main
import (
"fmt"
"github.com/cobratbq/flagtag"
)
type Configuration struct {
Greeting string `flag:"greet,Hello,The greeting."`
Name string `flag:"name,User,The user's name."`
Times int `flag:"times,1,Number of repeats."`
}
func main() {
var config Configuration
flagtag.MustConfigureAndParse(&config)
for i := 0; i < config.Times; i++ {
fmt.Printf("%s %s!\n", config.Greeting, config.Name)
}
}