getopt-like behavior in Go

前端 未结 9 725
南笙
南笙 2021-02-07 11:33

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?

9条回答
  •  旧巷少年郎
    2021-02-07 11:58

    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!
    

提交回复
热议问题