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?
Google has created a getopt package (import "github.com/pborman/getopt"
) which provides the more standard command line parsing (vs the 'flag' package).
package main
import (
"fmt"
"os"
"github.com/pborman/getopt"
)
func main() {
optName := getopt.StringLong("name", 'n', "", "Your name")
optHelp := getopt.BoolLong("help", 0, "Help")
getopt.Parse()
if *optHelp {
getopt.Usage()
os.Exit(0)
}
fmt.Println("Hello " + *optName + "!")
}
$ ./hello --help
Usage: hello [--help] [-n value] [parameters ...]
--help Help
-n, --name=value Your name
$ ./hello --name Bob
Hello Bob!