getopt-like behavior 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!
From the section "Command Line UI", you have several libraries able to parse getopt-long parameters.
I tried, with a Go1.0.2:
- the code.google.com/p/opts-go (See its documentation), which isn't quite operational.
- the github.com/droundy/goopt (See its documentation), which has a complete set of examples.
Example:
package main
import (
"fmt"
goopt "github.com/droundy/goopt"
)
func main() {
fmt.Println("flag")
goopt.NoArg([]string{"--abc"}, "abc param, no value", noabc)
goopt.Description = func() string {
return "Example program for using the goopt flag library."
}
goopt.Version = "1.0"
goopt.Summary = "goopt demonstration program"
goopt.Parse(nil)
}
func noabc() error {
fmt.Println("You should have an --abc parameter")
return nil
}
Other default parameters provided with goopt
:
--help Display the generated help message (calls Help())
--create-manpage Display a manpage generated by the goopt library (uses Author, Suite, etc)
--list-options List all known flags
Use the 'flag' package: http://golang.org/pkg/flag/. It doesn't do double-dash arguments, however. There isn't anything that exactly mimics GNU getopt behaviour (yet.)