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 to 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), while flags are optional settings that modify how the program behaves (e.g., -n).

In this chapter and the following three, we'll create a command-line tool named HIT alongside an efficient HTTP client package called HIT client. The HIT tool sends HTTP requests, measures, and reports HTTP server performance using the HIT client:

$ ./hit -n 1_000_000 -c 20 http://localhost:8082  #A
 __  __     __     ______
/\ \_\ \   /\ \   /\__  _\
\ \  __ \  \ \ \  \/_/\ \/
 \ \_\ \_\  \ \_\    \ \_\
  \/_/\/_/   \/_/     \/_/

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.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

4.4.3 Using Var

4.5 Positional arguments

4.5.1 Flags vs. positional arguments

4.5.2 Customizing usage messages

4.5.3 Setting a positional argument

4.6 Validation

4.6.1 Writing a custom validator

4.6.2 Validating flags with a custom validator

4.7 Exercises

4.8 Summary