Creating the Subcommands to Manage Hosts

Powerful Command-Line Applications in Go — by Ricardo Gerardi (77 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Starting the Scan Package | TOC | Testing the Manage Hosts Subcomman ds 👉

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

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

cobra/pScan.v3/cmd/root.go

​ ​func​ init() {
​ cobra.OnInitialize(initConfig)

​ ​// Here you will define your flags and configuration settings.​
​ ​// Cobra supports persistent flags, which, if defined here,​
​ ​// will be global for your application.​

​ rootCmd.PersistentFlags().StringVar(&cfgFile, ​"config"​, ​""​,
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.