Chapter 7
Using the Cobra CLI Framework

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

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

In this chapter, you’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[43] command. It allows you 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 you define the subcommand structure by associating these subcommands in a tree data structure. When done, your application will have this subcommand layout:

 pScan
 ├── completion
 ├── docs
 ├── help
 ├── hosts
 │   ├── add
 │   ├── delete
 │   └── list
 └── scan

The purpose of this application is to demonstrate how to use Cobra to help you create command-line applications and use Go to create networking applications. You can use this application to monitor your system, but remember to never port scan systems you don’t own.

Let’s install Cobra and use it to initialize this application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.66.208