Command line option parsing in go

There are a great many very cool things about go, but its builtin command line parsing package (flag) is not one of them. It lacks convenience, functionality and the generated help messages are plain ugly. Therefore I introduce: go-flags: https://github.com/jessevdk/go-flags. It has many features that the builtin package lacks and makes use of reflection to make it more convenient to specify command line options. It also has pretty printing of help messages :) go get it! (go get github.com/jessevdk/go-flags).

Example:

import(
    flags "github.com/jessevdk/go-flags"
    "os"
)

type Options struct {
    Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}

func main() {
     opts := new(Options)
     parser := flags.NewParser("testapp")

     parser.AddHelp(os.Stderr)
     parser.AddGroup(flags.NewGroup("Application Options", opts))
     
     args, err := parser.Parse(os.Args[1:])

     if err != nil {
         if err != flags.ErrHelp {
             parser.PrintError(os.Stderr, err)
         }

         os.Exit(1)
     }
}
This entry was posted in Uncategorized. Bookmark the permalink.

5 Responses to Command line option parsing in go

  1. Jim Campbell says:

    What kinds of things are you using Go for? I know that there are go-gtk and go-gtk3 bindings, but (afaik) they are pretty basic at this point.

    Are you using Go for your professional work?

    Just curious.

    • Jesse van den Kieboom says:

      I’m currently using go to rewrite some networking tools that I wrote for my work from C++ to go, and it’s a breeze. I really enjoy writing in go. I haven’t really looked at go gtk+ bindings much, mostly because I don’t really need that right now. I think go is very strong for standalone cli tools, but I’m not sure how well it would do for big GUI applications.

  2. Mike Durant says:

    Hi,

    I’ve try your example but i must have miss something as i got this kind of error message :
    # command-line-arguments
    ./main.go:15: not enough arguments in call to flags.NewParser
    ./main.go:17: parser.AddHelp undefined (type *flags.Parser has no field or method AddHelp)
    ./main.go:18: cannot use flags.NewGroup(“Application Options”, opts) (type *flags.Group) as type string in function argument
    ./main.go:18: not enough arguments in call to parser.AddGroup
    ./main.go:20: too many arguments in call to parser.Parse
    ./main.go:23: invalid operation: err != flags.ErrHelp (mismatched types error and flags.ErrorType)
    ./main.go:24: parser.PrintError undefined (type *flags.Parser has no field or method PrintError)

    (tested on go 1.0.3)

  3. Mike Durant says:

    thanks !

    great work.

Leave a Reply

Your email address will not be published. Required fields are marked *