This chapter covers
- Structuring and writing user-friendly command-line tools
- Parsing command-line arguments and flags
- Exploring the standard library’s
os
andflag
packages - Extending the
flag
package with custom types
Command-line tools are essential for automating tasks, running programs, and improving productivity. Compared with graphical interfaces, command-line tools offer faster, more customizable ways to handle repetitive tasks with greater consistency and fewer errors.
This chapter introduces parsing flags and arguments using the standard library’s os
and flag
packages. Arguments are typically the necessary parameters for the program (i.e., a URL), whereas flags are optional settings that modify how the program behaves (e.g., -n
).
In this chapter and the following three chapters, we’ll create a command-line tool named HIT alongside a concurrent HTTP client called HIT client. The HIT tool sends HTTP requests and measures and reports HTTP server performance using the HIT client:
$ ./hit -n 1_000_000 -c 20 http://localhost:8082 #1 __ __ __ ______ /\ \_\ \ /\ \ /\__ _\ \ \ __ \ \ \ \ \/_/\ \/ \ \_\ \_\ \ \_\ \ \_\ \/_/\/_/ \/_/ \/_/ Sending 1000000 requests to "http://localhost:8082" (concurrency: 20) Summary: Success: 100% RPS: 97854.73 Requests: 1000000 Errors: 0 Bytes: 12000000 Duration: 10.22s Fastest: 1ms Slowest: 5ms