Navigating Your New Cobra Application
Powerful Command-Line Applications in Go — by Ricardo Gerardi (74 / 127)
👈 Starting Your Cobra Application | TOC | Adding the First Subcommand to Your Application 👉
Cobra structures your application by creating a simple main.go file that only imports the package cmd and executes the application. The main.go file looks like this:
/*
Copyright © 2020 The Pragmatic Programmers, LLC
Copyrights apply to this source code.
Check LICENSE for details.
*/
package main
import "pragprog.com/rggo/cobra/pScan/cmd"
func main() {
cmd.Execute()
}
The core functionality of your application resides in the cmd package. When you run the command, the main function calls cmd.Execute to execute the root command of your application. You can find this function and the general structure of the program in the cmd/root.go file. The Execute function executes the rootCmd.Execute method on an instance of the cobra.Command type:
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
The cobra.Command type is the main type in the Cobra library. It represents a command or subcommand that your tool executes. You can combine commands in a parent-child relationship to form a tree structure of…