Mastering CLIs

Mastering CLIs

E44317a06f6ff5fec214d3f54f7ba432?s=128

Johannes Pichler

April 24, 2019
Tweet

Transcript

  1. MASTERING CLIS GOPHERS LINZ

  2. A TYPICAL GO APPLICATION

  3. TODO CLI APPLICATION todos list todos new --text="a new todo"

    todos complete --id=1
  4. HANDLING COMMANDS

  5. args := os.Args[1:] if len(args) == 0 { fmt.Println("you need

    to provide a command") return } command := args[0] fmt.Printf("Command: %s\n", command)
  6. switch args[0] { case "list": fmt.Println("List todos") break case "new":

    fmt.Println("New Todo") break case "complete": fmt.Println("Complete Todo") break default: fmt.Println("Invalid command specified") break }
  7. FLAGS

  8. todos new --text="a new todo"

  9. todos new --text="todo" [new --text=todo]

  10. text := flag.String("text", "", "...") flag.Parse() fmt.Println(text)

  11. !

  12. ! FLAGSET

  13. newCommand := flag.NewFlagSet("new", flag.ExitOnError) text := newCommand.String("text", "", "text for

    new todo") newCommand.Parse(os.Args[2:]) fmt.Println(*text)
  14. STICKING IT TOGETHER

  15. args := os.Args[1:] if len(args) == 0 { fmt.Println("you need

    to provide a command") return } command := args[0] switch command { case "list": // ... break case "new": newCommand := flag.NewFlagSet("new", flag.ExitOnError) text := newCommand.String("text", "", "text for new todo") newCommand.Parse(args[1:]) // ... break case "complete": completeCommand := flag.NewFlagSet("complete", flag.ExitOnError) id := completeCommand.Int("id", 0, "id to complete") completeCommand.Parse(args[1:]) // ... break }
  16. None
  17. COBRA Many of the most widely used Go projects are

    built using Cobra, such as: Kubernetes, Hugo, rkt, etcd, Moby (former Docker), Docker (distribution), OpenShift, Delve, GopherJS, CockroachDB, Bleve, ProjectAtomic (enterprise), Giant Swarm's gsctl, Nanobox/Nanopack, rclone, nehm, Pouch, Istio, Prototool, mattermost-server, etc.
  18. DEMO

  19. RESOURCES > https://gobyexample.com/command-line-flags > https://github.com/spf13/cobra > https://github.com/spf13/viper

  20. THANKS