Search⌘ K

Reading and Writing Configuration Files

Explore how to read and write configuration files in Go with the Viper library. Understand setting config paths, reading settings, and safely updating config files for advanced program customization.

Reading configuration files

After we did all the hard work of setting the search path and configuration name and type (or configuration filename), we can finally read and use the configuration. Viper provides a single viper.ReadInConfig() function for this.

That’s all it takes to mobilize the entire configuration file infrastructure and load the contents into Viper, where it is available through the standard access functions (unless overridden by higher priority configuration sources).

For example, here is a TOML configuration file:

[section-1]
key-1 = "value-1"
key-2 = "value-2"

[section-2]
key-3 = "value-3"
key-4 = "value-4"

Let’s save it as config.toml and read it in our program:

func main() {
	viper.SetConfigFile("config.toml")

	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(viper.Sub("sectio
...