How to Use koanf as a Viper Alternative

Replace Viper with Koanf by initializing a new instance, loading your config file with a parser, and reading values using dot-delimited keys.

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")
  1. Install the Koanf library and its YAML parser provider. go get github.com/knadh/koanf/v2 github.com/knadh/koanf/parsers/yaml
  2. Create a new Koanf instance with a custom delimiter. k := koanf.New(".")
  3. Load your configuration file using the file provider and YAML parser. k.Load(file.Provider("config.yaml"), yaml.Parser(), nil)
  4. Retrieve configuration values using the dot-delimited key path. port := k.Int("server.port")