...

/

Integrating Cobra and Viper

Integrating Cobra and Viper

In this lesson, you will see the synergy between Cobra and Viper in action using our demo calculator application.

We'll cover the following...

Integrating Cobra and Viper

To make things interesting, we will add two integers that will cause an overflow and see how playing with the configuration and command-line flags influences the result.

First, we will add a configuration file called config.toml with a key called check set to false:

check = false

The main function will use Viper to read this configuration file:

package main

import (
	"log"

	"github.com/spf13/viper"

	"gigi/calc/cmd"
)

func main() {
	viper.SetConfigFile("config.toml")
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatal(err)
	}

	cmd.Execute()
}

We’re ready for some experiments. Let’s pick two large numbers that will cause an overflow. Note that the Go int type is not well defined, so on your machine the maximal integer might be different. However, an int is always at least 32-bit. On my machine, it is 64-bit, so the max signed int value is 9223372036854775807.

Let’s see what happens if we try to add 1 to it.

$ go run main.go add
...