codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

Ā© 2026 codingstuff.io. All rights reserved.

Built with ā¤ļø for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

46 / 72 topics
42Third-Party Libraries Overview43GORM (Object-Relational Mapping)44Gin Framework45Echo Framework46Cobra CLI Library47Viper Config Library48Go Bindata for Embedding Assets49gRPC (Remote Procedure Calls)50Protocol Buffers
Tutorials/Go (Golang)/Cobra CLI Library
🐹Go (Golang)

Cobra CLI Library

Updated 2026-04-20
3 min read

Cobra CLI Library

The Cobra CLI library is a powerful tool for building command-line interfaces (CLIs) in Go, providing a robust framework that simplifies the creation of complex applications. This tutorial will walk you through the process of creating a basic CLI application using Cobra, including setting up your environment, defining commands, and handling flags.

Prerequisites

Before we dive into the tutorial, ensure you have the following installed:

  • Go (Golang) version 1.16 or later
  • A code editor or IDE of your choice (e.g., Visual Studio Code)

Setting Up Your Environment

To get started with Cobra, you need to install it using go get. Open your terminal and run the following command:

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

This command installs the Cobra CLI tool, which you can use to generate new Cobra projects.

Creating a New Project

To create a new project, navigate to your desired directory and run:

cobra init my-cli-app --pkgname=my-cli-app

This command initializes a new Cobra project named my-cli-app with the specified package name. The --pkgname flag is optional but recommended for clarity.

Project Structure

After running the above command, you'll see the following directory structure:

my-cli-app/
ā”œā”€ā”€ cmd/
│   └── root.go
ā”œā”€ā”€ main.go
└── go.mod
  • cmd/root.go: Contains the root command of your CLI.
  • main.go: Entry point of your application.
  • go.mod: Go module file for dependency management.

Defining Commands

Cobra uses a hierarchical command structure, where commands can have subcommands. Let's start by defining a simple hello command that prints "Hello, World!".

Step 1: Create the Command File

Inside the cmd directory, create a new file named hello.go.

package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
)

var helloCmd = &cobra.Command{
	Use:   "hello",
	Short: "Prints 'Hello, World!'",
	Long:  "A longer description that spans multiple lines and likely contains examples and usage of using your command.",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Hello, World!")
	},
}

func init() {
	rootCmd.AddCommand(helloCmd)
}

Step 2: Register the Command

In cmd/root.go, you'll see that the helloCmd is already registered to the root command. This is done by calling rootCmd.AddCommand(helloCmd) in the init function.

Step 3: Run Your CLI

Now, let's run your CLI application to see the new command in action. First, build your application:

go build -o my-cli-app

Then, execute the binary:

./my-cli-app hello

You should see the output:

Hello, World!

Handling Flags

Flags are a common way to pass options and arguments to CLI commands. Cobra makes it easy to define and handle flags.

Step 1: Define a Flag

Let's add a --name flag to our hello command that allows users to specify a name.

Modify cmd/hello.go as follows:

package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
)

var helloCmd = &cobra.Command{
	Use:   "hello",
	Short: "Prints 'Hello, World!'",
	Long:  "A longer description that spans multiple lines and likely contains examples and usage of using your command.",
	Run: func(cmd *cobra.Command, args []string) {
		name, _ := cmd.Flags().GetString("name")
		if name != "" {
			fmt.Printf("Hello, %s!\n", name)
		} else {
			fmt.Println("Hello, World!")
		}
	},
}

var name string

func init() {
	helloCmd.Flags().StringVarP(&name, "name", "n", "", "Name to greet")
	rootCmd.AddCommand(helloCmd)
}

Step 2: Use the Flag

Now, you can run your CLI with the --name flag:

./my-cli-app hello --name=Qwen

You should see the output:

Hello, Qwen!

Best Practices

  1. Modularize Commands: Keep your commands modular by placing them in separate files within the cmd directory.
  2. Use Flags Wisely: Only use flags when necessary to avoid cluttering the command interface.
  3. Handle Errors Gracefully: Always handle potential errors, especially when dealing with external resources or user input.
  4. Document Commands: Provide clear and concise documentation for each command using the Short and Long fields.

Conclusion

Cobra is a versatile library that simplifies the process of building robust CLI applications in Go. By following this tutorial, you've learned how to set up a basic CLI project, define commands, handle flags, and apply best practices. As you continue to develop your application, consider exploring additional features such as persistent flags, command aliases, and subcommands.

With Cobra, the possibilities for creating powerful and user-friendly CLIs are endless. Happy coding!


PreviousEcho FrameworkNext Viper Config Library

Recommended Gear

Echo FrameworkViper Config Library