Go CLI Interactions with Cobra

Simple example to start with Go CLI Interactions with Cobra

Refer : https://github.com/spf13/cobra

 

Sample example to start with :

package main

import (
   "fmt"
   "strings"

   cli "github.com/spf13/cobra"
)

func main() {
   var echoTimes int

   var cmdPrint = &cli.Command{
      Use:   "print [string to print]",
      Short: "Print anything to the screen",
      Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
      Args: cli.MinimumNArgs(1),
      Run: func(cmd *cli.Command, args []string) {
         fmt.Println("Print: " + strings.Join(args, " "))
      },
   }

   var cmdEcho = &cli.Command{
      Use:   "echo [string to echo]",
      Short: "Echo anything to the screen",
      Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,
      Args: cli.MinimumNArgs(1),
      Run: func(cmd *cli.Command, args []string) {
         fmt.Println("Print: " + strings.Join(args, " "))
      },
   }

   var cmdTimes = &cli.Command{
      Use:   "times [# times] [string to echo]",
      Short: "Echo anything to the screen more times",
      Long: `echo things multiple times back to the user by providing
a count and a string.`,
      Args: cli.MinimumNArgs(1),
      Run: func(cmd *cli.Command, args []string) {
         for i := 0; i < echoTimes; i++ {
            fmt.Println("Echo: " + strings.Join(args, " "))
         }
      },
   }

   cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

   var rootCmd = &cli.Command{Use: "app"}
   rootCmd.AddCommand(cmdPrint, cmdEcho)
   cmdEcho.AddCommand(cmdTimes)
   rootCmd.Execute()
}

 

esumits-MacBook-Pro:godev esumit$ go build gocobra.go
esumits-MacBook-Pro:godev esumit$ go run gocobra.go
Usage:
app [command]

Available Commands:
echo Echo anything to the screen
help Help about any command
print Print anything to the screen

Flags:
-h, –help help for app

Use “app [command] –help” for more information about a command

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s