Reading and Writing Configuration Files

Now, you'll earn to read and write these configuration files.

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("section-1").AllSettings())
		fmt.Println(viper.Sub("section-2").AllSettings())
	}
}


Output:

map[key-1:value-1 key-2:value-2]
map[key-3:value-3 key-4:value-4]

Note that use of the viper.Sub() function, which returns a sub-tree of the configuration as a separate Viper instance.

Get hands-on with 1400+ tech skills courses.