Skip to content

Instantly share code, notes, and snippets.

@wolfeidau
Created December 7, 2017 00:29
Show Gist options
  • Save wolfeidau/dab463a94ed7b0ab2d6b390bae36bd05 to your computer and use it in GitHub Desktop.
Save wolfeidau/dab463a94ed7b0ab2d6b390bae36bd05 to your computer and use it in GitHub Desktop.
Example of a more complex kingpin setup.
package main
import (
"fmt"
"os"
"github.com/alecthomas/kingpin"
)
var (
app = kingpin.New("chat", "A command-line chat application.")
verbose = app.Flag("verbose", "Verbose mode.").Short('v').Bool()
username = app.Flag("username", "Username used to authenticate to service.").Required().String()
password = app.Flag("password", "Password used to authenticate to service.").Required().String()
register = app.Command("register", "Register a new user.")
post = app.Command("post", "Post a message to a channel.")
)
type RegisterFlags struct {
RegisterNick string
}
type PostFlags struct {
PostNick string
}
func registerSetup() *RegisterFlags {
rf := &RegisterFlags{}
register.Flag("nick", "The nick name you want to register.").Short('n').StringVar(&rf.RegisterNick)
return rf
}
func postSetup() *PostFlags {
rf := &PostFlags{}
post.Flag("nick", "The nick name you want to register.").Short('n').StringVar(&rf.PostNick)
return rf
}
func main() {
rf := registerSetup()
pf := postSetup()
switch kingpin.MustParse(app.Parse(os.Args[1:])) {
// Register user
case register.FullCommand():
fmt.Println("Register", rf)
// Post message
case post.FullCommand():
fmt.Println("Post", pf)
}
}
@wolfeidau
Copy link
Author

$ go run cmd/kingpinlol/main.go --help-long
usage: chat --username=USERNAME --password=PASSWORD [<flags>] <command> [<args> ...]

A command-line chat application.

Flags:
      --help               Show context-sensitive help (also try --help-long and --help-man).
  -v, --verbose            Verbose mode.
      --username=USERNAME  Username used to authenticate to service.
      --password=PASSWORD  Password used to authenticate to service.

Commands:
  help [<command>...]
    Show help.


  register [<flags>]
    Register a new user.

    -n, --nick=NICK  The nick name you want to register.

  post [<flags>]
    Post a message to a channel.

    -n, --nick=NICK  The nick name you want to register.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment