Simple, extremely lightweight, extensible, configuration management library for Go. Supports JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to v
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.
…See the list of all bundled Providers and Parsers.
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.app.server.port. Any delimiter can be chosen.With these two interface implementations, koanf can obtain configuration in any format from any source, parse it, and make it available to an application.
…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.
…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.
……// 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)
}The bundled rawbytes Provider can be used to read arbitrary bytes from a source, like a database or an HTTP call.
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"))
}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
…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.
…The bundled confmap provider takes a map[string]any that can be loaded into a koanf instance.
…The bundled structs provider can be used to read data from a struct to load into a koanf instance.
…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
key: [1,2,3]second.yml
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.
app.server.port and APP.SERVER.port are not the same.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.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.
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.
…See the full API documentation of all available methods at https://pkg.go.dev/github.com/knadh/koanf/v2#section-documentation
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. |
Install with `go get
No open issues yet, or sync has not completed.