blog bg

May 26, 2025

How to Create a CLI Application in Go with Cobra and Viper

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

 

You can build an advanced command-line application with a little effort in Go. It is quick, easy, and has a great library environment. Cobra and Viper are popular CLI app builders. This post will show you how to combine these two libraries to build a customizable CLI application that scales and manages environments. This tutorial covers CLI development optimization for beginners and experts. 

 

What is Cobra and Viper?

Let's explore Cobra and Viper before digging into the code. Go's Cobra library creates command-line apps. Command, flag, and parameter parsing are easy with it. It simplifies your life by rapidly building complex command structures that are simple to handle. 

Viper is a configuration management library. It streamlines configuration files, environment variables, and flags. The powerful pair of Cobra and Viper lets you manage commands and setups without any boilerplate. I will show how this combination optimizes workflow. 

 

Setting Up the Project

Let's dive in and start working on the project. First, you need to have Go installed on your computer. Once you are ready, it is time to set up a new Go module for your project. 

Open your terminal and type: 

 

go mod init my-cli-app

Now, let's install Cobra and Viper. This is as easy as running:

 

go get -u github.com/spf13/cobra
go get -u github.com/spf13/viper

Now that the requirements are set up, you can start making your app. Create a new file named "main."Go to the project directory, and let's start by setting up a simple Cobra script. 

 

Creating a Basic Cobra Command 

Now, let's build the main part of our CLI app. Cobra is mainly about commands. Every CLI tool has a main command, and we will begin with that. In your main.go define the root command like this: 

 

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:   "mycli",
    Short: "A brief description of your application",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("Hello from CLI!")
    },
}

func main() {
    rootCmd.Execute()
}

This code creates a basic command line interface (CLI) called mycli. When you open the application, it will display "Hello from CLI!" in your terminal. The Execute() method runs the command. 

You can add more commands by making subcommands, like this: 

 

var greetCmd = &cobra.Command{
    Use:   "greet",
    Short: "Prints a greeting message",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("Hello there!")
    },
}

func init() {
    rootCmd.AddCommand(greetCmd)
}

This adds a command that shows a message. When you type mycli welcome, you will see (Hello there!) appear in the window. 

 

Integrating Viper for Configuration 

Right now, your CLI can take commands, but we can improve it by adding configurations using Viper. Instead of hardcoding numbers in your application, you may want to set some options using a file or environment variables. 

This is where Viper stands out. Let's set up a setup file, like config.yaml, and bind flags to Viper. First, make a setup file and include some basic settings. 

 

app_name: MyCLI App
version: 1.0

Next, in your main.go, use Viper to read the config file. Modify the code to add this functionality:

 

package main

import (
    "fmt"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
)

var configFile string

var rootCmd = &cobra.Command{
    Use:   "mycli",
    Short: "A brief description of your application",
    Run: func(cmd *cobra.Command, args []string) {
        viper.SetConfigFile(configFile)
        if err := viper.ReadInConfig(); err != nil {
            fmt.Println("Error reading config file", err)
            return
        }
        fmt.Printf("App Name: %s\n", viper.GetString("app_name"))
        fmt.Printf("Version: %s\n", viper.GetString("version"))
    },
}

func init() {
    rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "Config file")
    viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
}

func main() {
    rootCmd.Execute()
}

In this code, we included a permanent configuration file flag to let users choose the path when executing the application. Viper scans the file and produces config.yaml values. 

 

Finalizing the CLI Application 

Now that we have basic functionality, we can finish our app. Add error handling to verify the config file or gracefully manage missing flags. For instance, check for missing configuration files and provide useful comments. 

To test the application you can run it like this:

 

mycli --config config.yaml

 

Conclusion

CLI application development using Go, Cobra, and Viper is enjoyable and rewarding. This lets you easily handle tricky commands and configurations. These tools will expand with your requirements as you add functionality, making designing complex CLI applications easy. Start exploring with Cobra and Viper to construct your next Go-powered CLI utility!

267 views

Please Login to create a Question