Adding the First Subcommand to Your Application

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Navigating Your New Cobra Applicati on | TOC | Starting the Scan Package 👉

After initializing the application, use the Cobra generator to add subcommands to it. The generator includes a file in the cmd directory for each subcommand. Each file includes boilerplate code for the subcommand. It also adds the subcommand to its parent, forming the tree-like structure.

Add a new subcommand called hosts to your application to manage hosts in the hosts list. By default, Cobra adds this subcommand to the root command:

​ ​$ ​​cobra​​ ​​add​​ ​​hosts​
​ Using config file: /home/ricardo/.cobra.yaml
​ hosts created at /home/ricardo/pragprog.com/rggo/cobra/pScan

At this point, your application directory looks like this:

​ ​$ ​​tree​
​ .
​ ├── cmd
​ │ ├── hosts.go
​ │ └── root.go
​ ├── go.mod
​ ├── go.sum
​ ├── LICENSE
​ └── main.go

​ 1 directory, 6 files

Edit the cmd/hosts.go file and change the command’s short description to provide a one-line summary of the command’s purpose. Edit the long description to provide additional information on how to use the command and its suboptions:

cobra/pScan.v2/cmd/hosts.go

​ ​/*​
​ ​Copyright © 2020 The Pragmatic Programmers, LLC​
​ ​Copyrights apply to this source code.​
​…

--

--

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.