I have never been quite happy with the flags packages available for Go, 
including the standard flags package as well as my own getopt packages (v1 and 
v2).  They are just too cumbersome to use.  I finally have come up with a 
solution that I like.  github.com/pborman/options 
<https://godoc.org/github.com/pborman/options>

The command line options are declared as a simple structure with struct tags, 
for example:

// Declare the command line flags.  The help information does not need to line 
up,
// I just think it looks prettier this way.
var opts = struct {
        Help    options.Help  `getopt:"--help           display help"`
        Name    string        `getopt:"--name=NAME      name of the widget"`
        Count   int           `getopt:"--count -c=COUNT number of widgets"`
        Verbose bool          `getopt:"-v               be verbose"`
        Timeout time.Duration `getopt:"--timeout        duration of run"`
}{
        Name: “gopher”,
}

func main() {
        // Assign args to the positional parameters.
        args := options.RegisterAndParse(&opts)

        fmt.Printf(“Name is: %s\n”, opts.Name)
        …
}

The command usage displayed by passing —help to the above program will look 
something like:

Usage: prog [-v] [-c COUNT] [--help] [--name NAME] [--timeout value] 
[parameters ...]
 -c, --count=COUNT  number of widgets
     --help         display help
     --name=NAME    name of the widget [gopher]
     --timeout=value
                    duration of run
 -v                 be verbose

The package is built on top of the github.com/pborman/getopt/v2 
<https://godoc.org/github.com/pborman/getopt/v2> package and as such they can 
be used together.  The options package also supports reading command line 
arguments from a file by using the options.Flags type.

I hope that some of you might find this helpful in writing command line 
programs.

    -Paul

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to