Search⌘ K
AI Features

Navigating the New Cobra Application

Explore how to set up a Go command-line application using the Cobra framework. Understand the main.go file, the root command structure, how to add descriptions, version flags, and initialize configurations to build a functional CLI tool.

Creating the main.go file

Cobra structures our 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:

Go (1.6.2)
/*
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()
}
Creating the main.go file

The core functionality of our application resides in the cmd package. When we run the command, the main() function calls cmd.Execute() to execute the root command of our application. We can find this function and the general structure of the program in the cmd/root.go file. The ...

...
Go (1.6.2)
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
The Execute() function
...