Member-only story
Reading Nested Configuration Data with Viper in Go
Viper is a powerful configuration management library for Go projects. Many well-known open-source projects in the Go community use Viper for managing configuration settings. In this article, we’ll explore how to use Viper to read nested configuration information within a struct.
Reading Nested Configuration Data
In real-world project development, you often encounter complex configuration data, including multi-level nesting of structures and slices within a struct. Reading such deeply nested configuration information using Viper’s GetXXX
functions can be cumbersome.
Viper provides two parsing functions, Unmarshal
and UnmarshalKey
, which make it convenient to read deeply nested configuration information. You can parse all or specific configuration data into data structures like structs, maps, and more.
Let’s explore their usage through sample code.
Directory structure:
├── configs
│ ├── default.yaml
│ └── test.yaml
├── go.mod
├── go.sum
└── main.go
Sample code:
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
v := viper.New()
v.SetConfigFile("./configs/default.yaml")
err := v.ReadInConfig()
if err != nil {
fmt.Println(err)
return
}
err = v.UnmarshalKey("user_data", &userData)
if err != nil {
fmt.Println(err)…