CHAPTER 2Advanced Command-Line Applications
In this chapter, you will learn how to use the flag
package to implement command-line applications with sub-commands. Then, you will see how you can enforce predictable behavior in your command-line applications using contexts. Finally, you will learn how to combine contexts and handling operating system signals in your application. Let's jump in.
Implementing Sub-commands
Sub-commands are a way to split the functionality of your command-line application into logically independent commands having their own options and arguments. You have a top-level command—your application—and then you have a set of sub-commands, each having its own options and arguments. For example, the Go toolchain is distributed as a single application, go
, which is the top-level command. As a Go developer, you will interact with its various functionalities via dedicated sub-commands such as build
, fmt
, and test
.
You will recall from Chapter 1 that to create a command-line application, you first created a FlagSet
object. For creating an application with sub-commands, you will create one FlagSet
object per sub-command. Then, depending on which sub-command is specified, the corresponding FlagSet
object is used to parse the remaining command-line arguments (see Figure 2.1).
Get Practical Go now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.