Go (Golang) / Building CLI Applications in Go
Building Interactive CLI Applications with Cobra
In this tutorial, you will learn how to use the Cobra library to build interactive CLI applications in Go. You'll understand how to create commands, subcommands, and flags using C…
Section overview
5 resourcesExplores how to build command-line applications using Go.
Building Interactive CLI Applications with Cobra
Introduction
This tutorial aims to educate you on how to use the Cobra library to build interactive Command Line Interface (CLI) applications using Go. We will learn how to create commands, subcommands, and add flags to our commands using Cobra.
By the end of this tutorial, you will be able to:
- Understand the basics of Cobra
- Build a CLI application using Cobra
- Create commands, subcommands, and flags
Prerequisites:
- Basic knowledge of Go programming
- Go installed on your system
Step-by-Step Guide
Cobra is a library that provides a simple interface to create powerful modern CLI interfaces, similar to git & go tools. Cobra is also an application that will generate your application scaffolding to rapidly develop a Cobra-based application.
In this guide, we will start by installing Cobra, creating a new project, and then creating our commands.
Installing Cobra
go get -u github.com/spf13/cobra/cobra
Creating a new project
mkdir mycli && cd mycli
cobra init --pkg-name mycli
This will create a new Cobra application.
Creating Commands
Commands represent actions. In cobra, we can create a new command using cobra.Command.
var cmd = &cobra.Command{
Use: "command_name",
Short: "Short description of the command",
Long: `Long description of the command`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
Code Examples
Let's create a hello command for our CLI app.
var helloCmd = &cobra.Command{
Use: "hello",
Short: "Prints out 'Hello, World!'",
Long: `A command to print out 'Hello, World!'`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
}
func init() {
rootCmd.AddCommand(helloCmd)
}
In the above code:
- helloCmd is the command we are creating
- Use is the name of the command
- Short and Long are the descriptions of the command
- Run is the function that gets executed when the command is called
- rootCmd.AddCommand(helloCmd) adds the hello command to the root command
When you run your cli app with the hello command, it prints out Hello, World!.
Summary
In this tutorial, we learned about the Cobra library, how to create a new Cobra application, and how to create commands. We also saw a code example of creating a hello command.
Next, you can learn about creating subcommands, adding flags to commands, and more. Refer to the Cobra Documentation for more information.
Practice Exercises
- Create a
goodbyecommand that prints outGoodbye, World! - Create a
greetcommand that takes in a name as a flag and prints outHello, [name]!
Solutions
- The
goodbyecommand:
var goodbyeCmd = &cobra.Command{
Use: "goodbye",
Short: "Prints out 'Goodbye, World!'",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Goodbye, World!")
},
}
func init() {
rootCmd.AddCommand(goodbyeCmd)
}
- The
greetcommand:
var name string
var greetCmd = &cobra.Command{
Use: "greet",
Short: "Greets a user",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", name)
},
}
func init() {
greetCmd.Flags().StringVarP(&name, "name", "n", "", "Name to greet")
rootCmd.AddCommand(greetCmd)
}
In the greet command, we added a name flag using greetCmd.Flags().StringVarP(). This allows us to pass in a name when calling the greet command.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article