What getopt package I use for option handling in my Go programs
One of Go's famous issues is that the standard
flag package doesn't
handle command line options in the normal Unix getopt style. When
I started with Go this quite irritated me, and then later I gave
up and decided to use
flag anyway. Since
then, I've changed my mind again and now all of my recent Go programs
use a third party package that gives me more Unix-style option
handling. There are many of these packages; the one that I settled
on is github.com/pborman/getopt/v2.
(At one point I played around with github.com/spf13/cobra, but apparently it didn't stick. I think it was too complicated for the sort of small programs I usually write, which don't normally have sub-commands and so on.)
What I like about pborman/getopt is that it's straightforward to use and it gives you Unix style command handling with no fuss. I use the API format that uses existing variables, so my code tends to look like:
getopt.Flag(&oneline, 'l', "List one machine per line") getopt.FlagLong(&help, "help", 'h', "Print this help") [...]
The exception to this is counters, such as the usual
vp := getopt.Counter('v', "Increase verbosity for some operations")
Generally I've found the API straightforward, and I like that it's
relatively simple to add some additional help text after the flags
getopt.SetUsage() and so on. My programs not infrequently
have some extra usage information, but not enough to call for a
full separate option to dump it out; tacking it on the end of the
flags is my usual approach.
(This is where I point to the GoDoc for a full API reference.)
A lot of people seem to like the Kingpin package; I know that many Prometheus programs use it, for example, as does Square's certigo and acmetool. If I had complicated needs I would probably look into it.
(Like Cobra, Kingpin handles sub-commands with sub-flags and so on. You can see an example of that in certigo.)
PS: Now that I look at GoDoc, this package doesn't seem to be very popular nowadays. Things like cobra, pflag, and Kingpin are reported as being used by many more packages. If you're afraid of package rot and other problems, this may influence your choice. On the other hand, I tend to think that Unix getopt style option handling probably doesn't need much further development.