Creating the Subcommands to Manage Hosts

Learn how to create subcommands to manage the hosts list.

Overview

The business logic for the hosts list is ready, so let’s write the code to manage the hosts list under the hosts subcommand. These commands are: add to add a new host to the list, delete to delete a host from the list, and list to print all hosts in the list.

These subcommands all require a file to save and load the hosts to. Before including these commands, we make a change to the root command to add a persistent flag --hosts-file, allowing the user to specify the name of the file they want to use to save the hosts to. A persistent flag makes it available to the command and all subcommands under that command. By adding this flag to the root command, we make it global, which makes sense in this case because all the subcommands under hosts and later the scan subcommand require it.

Updating the root.go file

To add the persistent flag, we edit the file cmd/root.go and then add the following line to the init() function:

Get hands-on with 1200+ tech skills courses.