4 Command-line interfaces

 

This chapter covers

  • Structuring and writing user-friendly command-line tools
  • Parsing command-line arguments and flags
  • Exploring the standard library’s os and flag 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

4.1 Groundwork

4.1.1 Implementing the first version

4.1.2 Running the first version

4.2 Flag parsing

4.2.1 Overview

4.2.2 Higher-order value parsers

4.2.3 Implementing a flag parser

4.2.4 Integration and setting sensible defaults

4.3 The flag package

4.3.1 Integration

4.3.2 Demonstration

4.4 Value parsers

4.4.1 Value interface

4.4.2 Satisfying the Value interface