Cobra simplifies the process of creating command-line interfaces (CLIs) by providing an easy way to define commands, flags, and help documentation. This tutorial will cover the installation of Cobra, creating a basic CLI application, and implementing subcommands and flags.

Prerequisites

Before we begin, ensure you have the following:

  • Go installed on your machine (version 1.16 or higher).
  • A basic understanding of Go syntax and structure.

Installing Cobra

To start using Cobra, you need to install it. Open your terminal and run the following command:

go get -u github.com/spf13/cobra@latest

This command fetches the latest version of Cobra and adds it to your Go module.

Creating a Basic CLI Application

  1. Initialize a New Go Module

Create a new directory for your project and initialize a Go module:

   mkdir mycli
   cd mycli
   go mod init mycli
  1. Create the Main Application File

Create a file named main.go in the mycli directory:

   package main

   import (
       "fmt"
       "os"

       "github.com/spf13/cobra"
   )

   func main() {
       var rootCmd = &cobra.Command{
           Use:   "mycli",
           Short: "My CLI is a simple command-line application",
           Long:  `A longer description of My CLI application that can span multiple lines.`,
           Run: func(cmd *cobra.Command, args []string) {
               fmt.Println("Welcome to My CLI!")
           },
       }

       if err := rootCmd.Execute(); err != nil {
           fmt.Println(err)
           os.Exit(1)
       }
   }
  1. Run the Application

In your terminal, run the following command to execute your application:

   go run main.go

You should see the output:

   Welcome to My CLI!

Adding Subcommands

Cobra allows you to create subcommands to extend the functionality of your CLI. Let’s add a greet command that greets a user.

  1. Create the Greet Command

Modify your main.go file to include a new command:

   var greetCmd = &cobra.Command{
       Use:   "greet [name]",
       Short: "Greet a user by name",
       Long:  `A command to greet a user by their name.`,
       Args:  cobra.ExactArgs(1),
       Run: func(cmd *cobra.Command, args []string) {
           name := args[0]
           fmt.Printf("Hello, %s!\n", name)
       },
   }
  1. Register the Greet Command

Update the main function to register the greet command:

   func main() {
       var rootCmd = &cobra.Command{Use: "mycli"}

       rootCmd.AddCommand(greetCmd)

       if err := rootCmd.Execute(); err != nil {
           fmt.Println(err)
           os.Exit(1)
       }
   }
  1. Run the Greet Command

Now, run the greet command:

   go run main.go greet John

You should see:

   Hello, John!

Adding Flags

Flags are used to provide additional options to commands. Let's add a --shout flag to the greet command that modifies the greeting.

  1. Define the Flag

Update the greetCmd to include a flag:

   var shout bool

   func init() {
       greetCmd.Flags().BoolVarP(&shout, "shout", "s", false, "Shout the greeting")
   }
  1. Modify the Run Function

Update the Run function to check for the shout flag:

   Run: func(cmd *cobra.Command, args []string) {
       name := args[0]
       greeting := fmt.Sprintf("Hello, %s!", name)

       if shout {
           greeting = strings.ToUpper(greeting)
       }

       fmt.Println(greeting)
   },
  1. Run with the Flag

Now, you can run the command with the --shout flag:

   go run main.go greet John --shout

The output will be:

   HELLO, JOHN!

Summary of Features

FeatureDescription
SubcommandsEasily add subcommands to organize functionality.
FlagsProvide additional options to commands.
Help DocumentationAutomatically generated help text for commands and flags.

Best Practices

  • Organize Commands: For larger applications, consider organizing commands in separate files or directories.
  • Use Meaningful Names: Choose clear and descriptive names for commands and flags to enhance usability.
  • Error Handling: Implement proper error handling to provide feedback to users.

Learn more with useful resources