Chapter 7 Using the Cobra CLI Framework
Powerful Command-Line Applications in Go — by Ricardo Gerardi (72 / 127)
👈 Wrapping Up | TOC | Starting Your Cobra Application 👉
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…