Replace Viper with Koanf by initializing a Koanf instance, adding a file source, and reading values directly into your struct or map.
import (
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
)
k := koanf.New(".")
if err := k.Load(file.Provider("config.yaml"), yaml.Parser(), nil); err != nil {
panic(err)
}
port := k.Int("server.port")
- Install the Koanf library and its YAML parser provider.
go get github.com/knadh/koanf/v2 github.com/knadh/koanf/parsers/yaml - Create a new Koanf instance with a custom delimiter.
k := koanf.New(".") - Load your configuration file using the file provider and YAML parser.
k.Load(file.Provider("config.yaml"), yaml.Parser(), nil) - Retrieve configuration values using the dot-delimited key path.
port := k.Int("server.port")