Basic calculator CLI using Cobra and Viper
Let us pull some of the pieces together and create a separate and simple CLI using the Cobra CLI framework and Viper for configuration. A simple idea that we can easily implement is a basic calculator that can add, subtract, multiply, and divide values. The code for this demo exists within the Chapter-4-Demo
repository for you to follow along.
The Cobra CLI commands
The commands are created with the following cobra-cli
command calls:
cobra-cli add add cobra-cli add subtract cobra-cli add multiply cobra-cli add divide
Calling these commands successfully generates the code for each command, ready for us to fill in the details. Let us show each command and how they each are similar and different.
The add command
The add
command, addCmd
, is defined as a pointer to the cobra.Command
type. Here, we set the fields for the command:
// addCmd represents the add command var addCmd = &cobra.Command{ Use...