Go (Golang) / Building CLI Applications in Go

Building Interactive CLI Applications with Cobra

In this tutorial, you will learn how to use the Cobra library to build interactive CLI applications in Go. You'll understand how to create commands, subcommands, and flags using C…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores how to build command-line applications using Go.

Building Interactive CLI Applications with Cobra

Introduction

This tutorial aims to educate you on how to use the Cobra library to build interactive Command Line Interface (CLI) applications using Go. We will learn how to create commands, subcommands, and add flags to our commands using Cobra.

By the end of this tutorial, you will be able to:

  • Understand the basics of Cobra
  • Build a CLI application using Cobra
  • Create commands, subcommands, and flags

Prerequisites:
- Basic knowledge of Go programming
- Go installed on your system

Step-by-Step Guide

Cobra is a library that provides a simple interface to create powerful modern CLI interfaces, similar to git & go tools. Cobra is also an application that will generate your application scaffolding to rapidly develop a Cobra-based application.

In this guide, we will start by installing Cobra, creating a new project, and then creating our commands.

Installing Cobra

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

Creating a new project

mkdir mycli && cd mycli
cobra init --pkg-name mycli

This will create a new Cobra application.

Creating Commands

Commands represent actions. In cobra, we can create a new command using cobra.Command.

var cmd = &cobra.Command{
   Use:   "command_name",
   Short: "Short description of the command",
   Long: `Long description of the command`,
   Run: func(cmd *cobra.Command, args []string) {
     // Do Stuff Here
   },
}

Code Examples

Let's create a hello command for our CLI app.

var helloCmd = &cobra.Command{
   Use:   "hello",
   Short: "Prints out 'Hello, World!'",
   Long: `A command to print out 'Hello, World!'`,
   Run: func(cmd *cobra.Command, args []string) {
     fmt.Println("Hello, World!")
   },
}

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

In the above code:
- helloCmd is the command we are creating
- Use is the name of the command
- Short and Long are the descriptions of the command
- Run is the function that gets executed when the command is called
- rootCmd.AddCommand(helloCmd) adds the hello command to the root command

When you run your cli app with the hello command, it prints out Hello, World!.

Summary

In this tutorial, we learned about the Cobra library, how to create a new Cobra application, and how to create commands. We also saw a code example of creating a hello command.

Next, you can learn about creating subcommands, adding flags to commands, and more. Refer to the Cobra Documentation for more information.

Practice Exercises

  1. Create a goodbye command that prints out Goodbye, World!
  2. Create a greet command that takes in a name as a flag and prints out Hello, [name]!

Solutions

  1. The goodbye command:
var goodbyeCmd = &cobra.Command{
   Use:   "goodbye",
   Short: "Prints out 'Goodbye, World!'",
   Run: func(cmd *cobra.Command, args []string) {
     fmt.Println("Goodbye, World!")
   },
}

func init() {
   rootCmd.AddCommand(goodbyeCmd)
}
  1. The greet command:
var name string

var greetCmd = &cobra.Command{
   Use:   "greet",
   Short: "Greets a user",
   Run: func(cmd *cobra.Command, args []string) {
     fmt.Printf("Hello, %s!\n", name)
   },
}

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

In the greet command, we added a name flag using greetCmd.Flags().StringVarP(). This allows us to pass in a name when calling the greet command.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Age Calculator

Calculate age from date of birth.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help