5 Writing a Command-Line Tool
This chapter covers
- Writing and testing a CLI tool.
- Parsing and validating command-line arguments and flags.
- Extending the flag package with custom types.
A long time ago, alone at home, I was typing on the command line:
C:\> dir Volume in Drive C is MS_DOS_5 . . . C:\> A: A:\> PRINCE.EXE <<Prince of Persia video game starts>>
Since then, things have changed, but the command line still persists. Some people often prefer to work on the command line to get their tasks done quickly. Some command-line tools launch a web server, and others search for files or run your tests.
Imagine your team wants to make a command-line interface—as known as a CLI—tool called "hit" in Go to make concurrent requests to an HTTP server and gather performance metrics. You know the basics, but you don't know how to create and test a command-line tool in Go. In this chapter, I'll teach you to write an idiomatic, maintainable, and testable command-line tool from scratch using the Go Standard Library.
As you can see in Figure 5.1, a user runs the hit tool with a few command-line arguments (not shown in the figure) to check how an HTTP server performs. The tool makes the requests to the HTTP server, aggregates response statistics, and shows the result to the user.
Figure 5.1 The hit tool's bird's-eye view architecture.