Search⌘ K
AI Features

Integrating Cobra and Viper

Explore how to combine Cobra and Viper in your Go command-line programs to handle configuration files and command-line flags seamlessly. Learn to manage integer overflow checks by setting options in config files or overriding them with flags, enhancing flexibility and safety in your applications.

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 9223372036854775807 1
-9223372036854775808
...