How do I nicely parse a list of program parameters and automate handling \"--help\" and/or \"--version\" (such as \"program [-d value] [--abc] [FILE1]
\") in Go?
As a simple library, you have since August 2017 github.com/rsc/getopt
To use, define flags as usual with package flag. Then introduce any aliases by calling
getopt.Alias
:
getopt.Alias("v", "verbose")
Or call
getopt.Aliases
to define a list of aliases:
getopt.Aliases(
"v", "verbose",
"x", "xylophone",
)
And:
In general Go flag parsing is preferred for new programs, because it is not as pedantic about the number of dashes used to invoke a flag (you can write
-verbose
or--verbose
, and the program does not care).This package is meant to be used in situations where, for legacy reasons, it is important to use exactly getopt(3) syntax, such as when rewriting in Go an existing tool that already uses
getopt(3)
.