getopt-like behavior in Go

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

    Another option is Kingping which provides support for all the standard goodies you have come to expect from a modern command line parsing library. It has --help in multiple formats, sub-commands, requirements, types, defaults, etc. It's also still under development. It seems like the other suggestions here haven't been updated in a while.

    package main
    
    import (
      "os"
      "strings"
      "gopkg.in/alecthomas/kingpin.v2"
    )
    
    var (
      app      = kingpin.New("chat", "A command-line chat application.")
      debug    = app.Flag("debug", "Enable debug mode.").Bool()
      serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP()
    
      register     = app.Command("register", "Register a new user.")
      registerNick = register.Arg("nick", "Nickname for user.").Required().String()
      registerName = register.Arg("name", "Name of user.").Required().String()
    
      post        = app.Command("post", "Post a message to a channel.")
      postImage   = post.Flag("image", "Image to post.").File()
      postChannel = post.Arg("channel", "Channel to post to.").Required().String()
      postText    = post.Arg("text", "Text to post.").Strings()
    )
    
    func main() {
      switch kingpin.MustParse(app.Parse(os.Args[1:])) {
      // Register user
      case register.FullCommand():
        println(*registerNick)
    
      // Post message
      case post.FullCommand():
        if *postImage != nil {
        }
        text := strings.Join(*postText, " ")
        println("Post:", text)
      }
    }
    

    And the --help output:

    $ chat --help
    usage: chat []  [] [ ...]
    
    A command-line chat application.
    
    Flags:
      --help              Show help.
      --debug             Enable debug mode.
      --server=127.0.0.1  Server address.
    
    Commands:
      help []
        Show help for a command.
    
      register  
        Register a new user.
    
      post []  []
        Post a message to a channel.
    

提交回复
热议问题