Starting the Cobra Application

Learn how to handle the user interface of our program using the Cobra framework.

Overview

Up to this point, we’ve had to write all of the code to define the command-line interface for our programs. We’ve had to handle flags, environment variables, and the execution logic. Cobra is a popular framework for designing CLI applications, and in this chapter, we’ll use it to handle the user interface of our program. If we work with Go and CLI tools, then it’s likely that we’ll encounter Cobra. Many modern tools are built with Cobra, including Kubernetes, Openshift, Podman, Hugo, and Docker.

Cobra provides a library that allows us to design CLI applications supporting POSIX -compliant flags, subcommands, suggestions, autocompletion, and automatic help creation. It integrates with Viper to provide management of configuration and environment variables for our applications. Cobra also provides a generator program that creates boilerplate code for us, allowing us to focus on our tool’s business logic.

What will we learn?

In this chapter, we’ll use Cobra to develop pScan, a CLI tool that uses subcommands, similar to Git or Kubernetes. This tool executes a TCP port scan on a list of hosts similarly to the Nmap command. It allows us to add, list, and delete hosts from the list using the subcommand hosts. It executes the scan on selected ports using the subcommand scan. Users can specify the ports using a command-line flag. It also features command completion using the subcommand completion and manual page generation with the subcommand docs. Cobra helps us define the subcommand structure by associating these subcommands in a tree data structure. When done, our application will have this subcommand layout:

Get hands-on with 1200+ tech skills courses.