CLI subcommand pattern¶
The CLI subcommand pattern is a design approach for command-line interfaces where a main executable acts as a dispatcher for more specific functions, often referred to as "subcommands." Instead of a utility accepting all arguments through a single set of flags, the executable interprets the first argument (e.g., get, add) to determine which specific operation to execute^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
Structure¶
Implementing this pattern typically involves three main architectural components^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]:
- Flag Definition: Creating a dedicated
FlagSetfor each subcommand to define its specific arguments and options. For example,getCmd := flag.NewFlagSet("get", flag.ExitOnError)creates a parser specifically for thegetoperation^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. - Routing: Using a control flow statement (like a
switchstatement) to inspect the primary argument (e.g.,os.Args[1]) and direct execution to the appropriate handler function^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. - Parsing: Specifically parsing the argument list slice starting from the index after the subcommand (e.g.,
os.Args[2:]) so that the subcommand's flag parser only sees its relevant flags^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
Input Handling¶
A key aspect of this pattern is the validation of input at the subcommand level^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. This involves checking that required flags are present and valid. For example:
getcommand: Validates that either an--idis provided or the--allflag is set to retrieve the full list^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].addcommand: Validates that multiple fields—such as ID, title, URL, and description—are present before constructing the data object to be saved^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
Related Concepts¶
- [[Flag parsing]]
- Standard input/output
- [[Scripting language]]
Sources¶
^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]