Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
K

koanf

> DevOps
Open source

Simple, extremely lightweight, extensible, configuration management library for Go. Supports JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to v

4.1K stars0 likes2 views
WebsiteGitHub

About

Simple, extremely lightweight, extensible, configuration management library for Go. Supports JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to v

koanf is a library for reading configuration from different sources in different formats in Go applications. It is a cleaner, lighter alternative to spf13/viper with better abstractions and extensibility and far fewer dependencies.

koanf v2 has modules (Providers) for reading configuration from a variety of sources such as files, command line flags, environment variables, Vault, and S3 and for parsing (Parsers) formats such as JSON, YAML, TOML, HUML, Hashicorp HCL. It is easy to plug in custom parsers and providers.

All external dependencies in providers and parsers are detached from the core and can be installed separately as necessary.

Installation

…

See the list of all bundled Providers and Parsers.

Contents

  • Concepts
  • Reading config from files
  • Watching file for changes
  • Reading from command line
  • Reading environment variables
  • Reading from an S3 bucket
  • Reading raw bytes
  • Reading from maps and structs
  • Unmarshalling and marshalling
  • Order of merge and key case sensitivity
  • Custom Providers and Parsers
  • Custom merge strategies
  • List of installable Providers and Parsers

Concepts

  • koanf.Provider is a generic interface that provides configuration, for example, from files, environment variables, HTTP sources, or anywhere. The configuration can either be raw bytes that a parser can parse, or it can be a nested map[string]any that can be directly loaded.
  • koanf.Parser is a generic interface that takes raw bytes, parses, and returns a nested map[string]any. For example, JSON and YAML parsers.
  • Once loaded into koanf, configuration are values queried by a delimited key path syntax. eg: app.server.port. Any delimiter can be chosen.
  • Configuration from multiple sources can be loaded and merged into a koanf instance, for example, load from a file first and override certain values with flags from the command line.

With these two interface implementations, koanf can obtain configuration in any format from any source, parse it, and make it available to an application.

Reading config from files

…

Watching file for changes

Some providers expose a Watch() method that makes the provider watch for changes in configuration and trigger a callback to reload the configuration. This is not goroutine safe if there are concurrent *Get() calls happening on the koanf object while it is doing a Load(). Such scenarios will need mutex locking.

file, appconfig, vault, consul providers have a Watch() method.

…

Reading from command line

The following example shows the use of posflag.Provider, a wrapper over the spf13/pflag library, an advanced commandline lib. For Go's built in flag package, use basicflag.Provider.

…

Reading environment variables

…

Reading from an S3 bucket

go
// Load JSON config from s3.
if err := k.Load(s3.Provider(s3.Config{
	AccessKey: os.Getenv("AWS_S3_ACCESS_KEY"),
	SecretKey: os.Getenv("AWS_S3_SECRET_KEY"),
	Region:    os.Getenv("AWS_S3_REGION"),
	Bucket:    os.Getenv("AWS_S3_BUCKET"),
	ObjectKey: "dir/config.json",
}), json.Parser()); err != nil {
	log.Fatalf("error loading config: %v", err)
}

Reading raw bytes

The bundled rawbytes Provider can be used to read arbitrary bytes from a source, like a database or an HTTP call.

go
package main

import (
	"fmt"

	"github.com/knadh/koanf/v2"
	"github.com/knadh/koanf/parsers/json"
	"github.com/knadh/koanf/providers/rawbytes"
)

// Global koanf instance. Use . as the key path delimiter. This can be / or anything.
var k = koanf.New(".")

func main() {
	b := []byte(`{"type": "rawbytes", "parent1": {"child1": {"type": "rawbytes"}}}`)
	k.Load(rawbytes.Provider(b), json.Parser())
	fmt.Println("type is = ", k.String("parent1.child1.type"))
}

Unmarshalling and marshalling

Parsers can be used to unmarshal and scan the values in a Koanf instance into a struct based on the field tags, and to marshal a Koanf instance back into serialized bytes, for example to JSON or YAML files

…

Unmarshalling with flat paths

Sometimes it is necessary to unmarshal an assortment of keys from various nested structures into a flat target structure. This is possible with the UnmarshalConf.FlatPaths flag.

…

Reading from nested maps

The bundled confmap provider takes a map[string]any that can be loaded into a koanf instance.

…

Reading from struct

The bundled structs provider can be used to read data from a struct to load into a koanf instance.

…

Merge behavior

Default behavior

The default behavior when you create Koanf this way is: koanf.New(delim) that the latest loaded configuration will merge with the previous one.

For example: first.yml

yaml
key: [1,2,3]

second.yml

yaml
key: 'string'

When second.yml is loaded it will override the type of the first.yml.

If this behavior is not desired, you can merge 'strictly'. In the same scenario, Load will return an error.

…

Note: When merging different extensions, each parser can treat his types differently, meaning even though you the load same types there is a probability that it will fail with StrictMerge: true.

For example: merging JSON and YAML will most likely fail because JSON treats integers as float64 and YAML treats them as integers.

Order of merge and key case sensitivity

  • Config keys are case-sensitive in koanf. For example, app.server.port and APP.SERVER.port are not the same.
  • koanf does not impose any ordering on loading config from various providers. Every successive Load() or Merge() merges new config into the existing config. That is, it is possible to load environment variables first, then files on top of it, and then command line variables on top of it, or any such order.

Custom Providers and Parsers

A Provider returns a nested map[string]any config that can be loaded directly into koanf with koanf.Load() or it can return raw bytes that can be parsed with a Parser (again, loaded using koanf.Load(). Writing Providers and Parsers are easy. See the bundled implementations in the providers and parsers directories.

Custom merge strategies

By default, when merging two config sources using Load(), koanf recursively merges keys of nested maps (map[string]any), while static values are overwritten (slices, strings, etc). This behaviour can be changed by providing a custom merge function with the WithMergeFunc option.

…

API

See the full API documentation of all available methods at https://pkg.go.dev/github.com/knadh/koanf/v2#section-documentation

Bundled Providers

Install with go get -u github.com/knadh/koanf/providers/$provider

Package Provider Description
file file.Provider(filepath string) Reads a file and returns the raw bytes to be parsed.
fs fs.Provider(f fs.FS, filepath string) (Experimental) Reads a file from fs.FS and returns the raw bytes to be parsed. The provider requires go v1.16 or higher.
basicflag basicflag.Provider(f *flag.FlagSet, delim string) Takes a stdlib flag.FlagSet
posflag posflag.Provider(f *pflag.FlagSet, delim string) Takes an spf13/pflag.FlagSet (advanced POSIX compatible flags with multiple types) and provides a nested config map based on delim.
env/v2 env.Provider(prefix, delim string, f func(s string) string) Takes an optional prefix to filter env variables by, an optional function that takes and returns a string to transform env variables, and returns a nested config map based on delim.
confmap confmap.Provider(mp map[string]any, delim string) Takes a premade map[string]any conf map. If delim is provided, the keys are assumed to be flattened, thus unflattened using delim.
structs structs.Provider(s any, tag string) Takes a struct and struct tag.
s3 s3.Provider(s3.S3Config{}) Takes a s3 config struct.
rawbytes rawbytes.Provider(b []byte) Takes a raw []byte slice to be parsed with a koanf.Parser
vault/v2 vault.Provider(vault.Config{}) Hashicorp Vault provider
appconfig/v2 vault.AppConfig(appconfig.Config{}) AWS AppConfig provider
etcd/v2 etcd.Provider(etcd.Config{}) CNCF etcd provider
consul/v2 consul.Provider(consul.Config{}) Hashicorp Consul provider
parameterstore/v2 parameterstore.Provider(parameterstore.Config{}) AWS Systems Manager Parameter Store provider
cliflagv2 cliflagv2.Provider(ctx *cli.Context, delimiter string) Reads commands and flags from urfave/cli/v2 context including global flags and nested command flags and provides a nested config map based on delim.
cliflagv3 cliflagv3.Provider(ctx *cli.Context, delimiter string) Reads commands and flags from urfave/cli/v3 and provides a nested config map based on delim.
kiln kiln.Provider(configPath, keyPath, file string) Takes an optional prefix to filter environment variables keys by, an optional function that takes and returns a string to transform environment variables, and returns a nested config map.

Bundled Parsers

Install with `go get

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goconfigconfig-loaderconfigurationconfiguration-file

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理