autoflags: github.com/artyom/autoflags Index | Examples | Files

package autoflags

import "github.com/artyom/autoflags"

Package autoflags provides a convenient way of exposing struct fields as command line flags. Exposed fields should have special tag attached:

var config = struct {
	Name    string `flag:"name,user name"`
	Age     uint   `flag:"age"`
	Married bool   // this won't be exposed
}{
	// default values
	Name: "John Doe",
	Age:  34,
}

After declaring your flags and their default values as above, just register flags with autoflags.Define and call flag.Parse() as usual:

autoflags.Define(&config)
flag.Parse()

Now config struct has its fields populated from command line flags. Call the program with flags to override default values:

progname -name "Jane Roe" -age 29

Package autoflags understands all basic types supported by flag's package xxxVar functions: int, int64, uint, uint64, float64, bool, string, time.Duration. Types implementing flag.Value interface are also supported. Attaching non-empty `flag` tag to field of unsupported type would result in panic.

Index

Examples

Package Files

autoflags.go

func Define Uses

func Define(config interface{})

Define takes pointer to struct and declares flags for its flag-tagged fields. Valid tags have one of the following formats:

`flag:"flagname"`
`flag:"flagname,usage string"`

Define would panic if given unsupported/invalid argument (anything but non-nil pointer to struct) or if any config attribute with `flag` tag is of type unsupported by the flag package (consider implementing flag.Value interface for such attributes).

func DefineFlagSet Uses

func DefineFlagSet(fs *flag.FlagSet, config interface{})

DefineFlagSet takes pointer to struct and declares flags for its flag-tagged fields on given FlagSet. Valid tags have one of the following formats:

`flag:"flagname"`
`flag:"flagname,usage string"`

DefineFlagSet would panic if given unsupported/invalid config argument (anything but non-nil pointer to struct) or if any config attribute with `flag` tag is of type unsupported by the flag package (consider implementing flag.Value interface for such attrubutes).

Code:

fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
var config = struct {
    Name    string `flag:"name,user name"`
    Age     uint   `flag:"age"`
    Married bool   // this won't be exposed
}{
    Name: "John Doe", // default values
    Age:  34,
}
DefineFlagSet(fs, &config)

args := []string{"-name", "Jane Roe", "-age", "29"}

fmt.Printf("before parsing flags:\n%+v\n", config)
fs.Parse(args)
fmt.Printf("\nafter parsing flags:\n%+v\n", config)

Output:

before parsing flags:
{Name:John Doe Age:34 Married:false}

after parsing flags:
{Name:Jane Roe Age:29 Married:false}

func Parse Uses

func Parse(config interface{})

Parse is a shortcut for:

autoflags.Define(&args)
flag.Parse()

Package autoflags imports 6 packages (graph) and is imported by 28 packages. Updated 2019-01-23. Refresh now. Tools for package owners.