getopt-like behavior in Go

前端 未结 9 711
南笙
南笙 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:55

    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
    

提交回复
热议问题