Debian Codegraph @

README.md

raw
1 <a href="https://zerodha.tech"><img src="https://zerodha.tech/static/images/github-badge.svg" align="right" /></a>
2
3 ![koanf](https://user-images.githubusercontent.com/547147/72681838-6981dd00-3aed-11ea-8f5d-310816c70c08.png)
4
5 **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](#alternative-to-viper) with better abstractions and extensibility and far fewer dependencies.
6
7 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.
8
9 All external dependencies in providers and parsers are detached from the core and can be installed separately as necessary.
10
11 [![Run Tests](https://github.com/knadh/koanf/actions/workflows/test.yml/badge.svg)](https://github.com/knadh/koanf/actions/workflows/test.yml) [![GoDoc](https://pkg.go.dev/badge/github.com/knadh/koanf?utm_source=godoc)](https://pkg.go.dev/github.com/knadh/koanf/v2)
12
13 ### Installation
14
15 ```shell
16 # Install the core.
17 go get -u github.com/knadh/koanf/v2
18
19 # Install the necessary Provider(s).
20 # Available: file, env/v2, posflag, basicflag, confmap, rawbytes,
21 # structs, fs, s3, appconfig/v2, consul/v2, etcd/v2, vault/v2, parameterstore/v2
22 # eg: go get -u github.com/knadh/koanf/providers/s3
23 # eg: go get -u github.com/knadh/koanf/providers/consul/v2
24
25 go get -u github.com/knadh/koanf/providers/file
26
27
28 # Install the necessary Parser(s).
29 # Available: toml, toml/v2, json, yaml, huml, dotenv, hcl, hjson, nestedtext
30 # go get -u github.com/knadh/koanf/parsers/$parser
31
32 go get -u github.com/knadh/koanf/parsers/toml
33 ```
34
35 [See the list](#api) of all bundled Providers and Parsers.
36
37 ### Contents
38
39 - [Concepts](#concepts)
40 - [Reading config from files](#reading-config-from-files)
41 - [Watching file for changes](#watching-file-for-changes)
42 - [Reading from command line](#reading-from-command-line)
43 - [Reading environment variables](#reading-environment-variables)
44 - [Reading from an S3 bucket](#reading-from-an-s3-bucket)
45 - [Reading raw bytes](#reading-raw-bytes)
46 - [Reading from maps and structs](#reading-from-nested-maps)
47 - [Unmarshalling and marshalling](#unmarshalling-and-marshalling)
48 - [Order of merge and key case sensitivity](#order-of-merge-and-key-case-sensitivity)
49 - [Custom Providers and Parsers](#custom-providers-and-parsers)
50 - [Custom merge strategies](#custom-merge-strategies)
51 - [List of installable Providers and Parsers](#api)
52
53 ### Concepts
54
55 - `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.
56 - `koanf.Parser` is a generic interface that takes raw bytes, parses, and returns a nested `map[string]any`. For example, JSON and YAML parsers.
57 - Once loaded into koanf, configuration are values queried by a delimited key path syntax. eg: `app.server.port`. Any delimiter can be chosen.
58 - 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.
59
60 With these two interface implementations, koanf can obtain configuration in any format from any source, parse it, and make it available to an application.
61
62 ### Reading config from files
63
64 ```go
65 package main
66
67 import (
68 "fmt"
69 "log"
70
71 "github.com/knadh/koanf/v2"
72 "github.com/knadh/koanf/parsers/json"
73 "github.com/knadh/koanf/parsers/yaml"
74 "github.com/knadh/koanf/providers/file"
75 )
76
77 // Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character.
78 var k = koanf.New(".")
79
80 func main() {
81 // Load JSON config.
82 if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil {
83 log.Fatalf("error loading config: %v", err)
84 }
85
86 // Load YAML config and merge into the previously loaded config (because we can).
87 k.Load(file.Provider("mock/mock.yml"), yaml.Parser())
88
89 fmt.Println("parent's name is = ", k.String("parent1.name"))
90 fmt.Println("parent's ID is = ", k.Int("parent1.id"))
91 }
92
93 ```
94
95 ### Watching file for changes
96 Some providers expose a `Watch()` method that makes the provider watch for changes
97 in configuration and trigger a callback to reload the configuration.
98 This is not goroutine safe if there are concurrent `*Get()` calls happening on the
99 koanf object while it is doing a `Load()`. Such scenarios will need mutex locking.
100
101 `file, appconfig, vault, consul` providers have a `Watch()` method.
102
103
104 ```go
105 package main
106
107 import (
108 "fmt"
109 "log"
110
111 "github.com/knadh/koanf/v2"
112 "github.com/knadh/koanf/parsers/json"
113 "github.com/knadh/koanf/parsers/yaml"
114 "github.com/knadh/koanf/providers/file"
115 )
116
117 // Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character.
118 var k = koanf.New(".")
119
120 func main() {
121 // Load JSON config.
122 f := file.Provider("mock/mock.json")
123 if err := k.Load(f, json.Parser()); err != nil {
124 log.Fatalf("error loading config: %v", err)
125 }
126
127 // Load YAML config and merge into the previously loaded config (because we can).
128 k.Load(file.Provider("mock/mock.yml"), yaml.Parser())
129
130 fmt.Println("parent's name is = ", k.String("parent1.name"))
131 fmt.Println("parent's ID is = ", k.Int("parent1.id"))
132
133 // Watch the file and get a callback on change. The callback can do whatever,
134 // like re-load the configuration.
135 // File provider always returns a nil `event`.
136 f.Watch(func(event any, err error) {
137 if err != nil {
138 log.Printf("watch error: %v", err)
139 return
140 }
141
142 // Throw away the old config and load a fresh copy.
143 log.Println("config changed. Reloading ...")
144 k = koanf.New(".")
145 k.Load(f, json.Parser())
146 k.Print()
147 })
148
149 // To stop a file watcher, call:
150 // f.Unwatch()
151
152 // Block forever (and manually make a change to mock/mock.json) to
153 // reload the config.
154 log.Println("waiting forever. Try making a change to mock/mock.json to live reload")
155 <-make(chan bool)
156 }
157 ```
158
159
160 ### Reading from command line
161
162 The following example shows the use of `posflag.Provider`, a wrapper over the [spf13/pflag](https://github.com/spf13/pflag) library, an advanced commandline lib. For Go's built in `flag` package, use `basicflag.Provider`.
163
164 ```go
165 package main
166
167 import (
168 "fmt"
169 "log"
170 "os"
171
172 "github.com/knadh/koanf/v2"
173 "github.com/knadh/koanf/parsers/toml"
174
175 // TOML version 2 is available at:
176 // "github.com/knadh/koanf/parsers/toml/v2"
177
178 "github.com/knadh/koanf/providers/file"
179 "github.com/knadh/koanf/providers/posflag"
180 flag "github.com/spf13/pflag"
181 )
182
183 // Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character.
184 var k = koanf.New(".")
185
186 func main() {
187 // Use the POSIX compliant pflag lib instead of Go's flag lib.
188 f := flag.NewFlagSet("config", flag.ContinueOnError)
189 f.Usage = func() {
190 fmt.Println(f.FlagUsages())
191 os.Exit(0)
192 }
193 // Path to one or more config files to load into koanf along with some config params.
194 f.StringSlice("conf", []string{"mock/mock.toml"}, "path to one or more .toml config files")
195 f.String("time", "2020-01-01", "a time string")
196 f.String("type", "xxx", "type of the app")
197 f.Parse(os.Args[1:])
198
199 // Load the config files provided in the commandline.
200 cFiles, _ := f.GetStringSlice("conf")
201 for _, c := range cFiles {
202 if err := k.Load(file.Provider(c), toml.Parser()); err != nil {
203 log.Fatalf("error loading file: %v", err)
204 }
205 }
206
207 // "time" and "type" may have been loaded from the config file, but
208 // they can still be overridden with the values from the command line.
209 // The bundled posflag.Provider takes a flagset from the spf13/pflag lib.
210 // Passing the Koanf instance to posflag helps it deal with default command
211 // line flag values that are not present in conf maps from previously loaded
212 // providers.
213 if err := k.Load(posflag.Provider(f, ".", k), nil); err != nil {
214 log.Fatalf("error loading config: %v", err)
215 }
216
217 fmt.Println("time is = ", k.String("time"))
218 }
219 ```
220
221 ### Reading environment variables
222
223 ```go
224 package main
225
226 import (
227 "fmt"
228 "log"
229 "strings"
230
231 "github.com/knadh/koanf/v2"
232 "github.com/knadh/koanf/parsers/json"
233 "github.com/knadh/koanf/providers/env/v2"
234 "github.com/knadh/koanf/providers/file"
235 )
236
237 // Global koanf instance. Use . as the key path delimiter. This can be / or anything.
238 var k = koanf.New(".")
239
240 func main() {
241 // Load JSON config.
242 if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil {
243 log.Fatalf("error loading config: %v", err)
244 }
245
246 // Load only environment variables with prefix "MYVAR_" and merge into config.
247 // Transform var names by:
248 // 1. Converting to lowercase
249 // 2. Removing "MYVAR_" prefix
250 // 3. Replacing "_" with "." to representing nesting using the . delimiter.
251 // Example: MYVAR_PARENT1_CHILD1_NAME becomes "parent1.child1.name"
252 k.Load(env.Provider(".", env.Opt{
253 Prefix: "MYVAR_",
254 TransformFunc: func(k, v string) (string, any) {
255 // Transform the key.
256 k = strings.ReplaceAll(strings.ToLower(strings.TrimPrefix(k, "MYVAR_")), "_", ".")
257
258 // Transform the value into slices, if they contain spaces.
259 // Eg: MYVAR_TAGS="foo bar baz" -> tags: ["foo", "bar", "baz"]
260 // This is to demonstrate that string values can be transformed to any type
261 // where necessary.
262 if strings.Contains(v, " ") {
263 return k, strings.Split(v, " ")
264 }
265
266 return k, v
267 },
268 }), nil)
269
270 fmt.Println("name is =", k.String("parent1.child1.name"))
271 fmt.Println("time is =", k.Time("time", time.DateOnly))
272 fmt.Println("ids are =", k.Strings("parent1.child1.grandchild1.ids"))
273 }
274 ```
275
276 ### Reading from an S3 bucket
277
278 ```go
279 // Load JSON config from s3.
280 if err := k.Load(s3.Provider(s3.Config{
281 AccessKey: os.Getenv("AWS_S3_ACCESS_KEY"),
282 SecretKey: os.Getenv("AWS_S3_SECRET_KEY"),
283 Region: os.Getenv("AWS_S3_REGION"),
284 Bucket: os.Getenv("AWS_S3_BUCKET"),
285 ObjectKey: "dir/config.json",
286 }), json.Parser()); err != nil {
287 log.Fatalf("error loading config: %v", err)
288 }
289 ```
290
291 ### Reading raw bytes
292
293 The bundled `rawbytes` Provider can be used to read arbitrary bytes from a source, like a database or an HTTP call.
294
295 ```go
296 package main
297
298 import (
299 "fmt"
300
301 "github.com/knadh/koanf/v2"
302 "github.com/knadh/koanf/parsers/json"
303 "github.com/knadh/koanf/providers/rawbytes"
304 )
305
306 // Global koanf instance. Use . as the key path delimiter. This can be / or anything.
307 var k = koanf.New(".")
308
309 func main() {
310 b := []byte(`{"type": "rawbytes", "parent1": {"child1": {"type": "rawbytes"}}}`)
311 k.Load(rawbytes.Provider(b), json.Parser())
312 fmt.Println("type is = ", k.String("parent1.child1.type"))
313 }
314 ```
315
316 ### Unmarshalling and marshalling
317 `Parser`s 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
318
319 ```go
320 package main
321
322 import (
323 "fmt"
324 "log"
325
326 "github.com/knadh/koanf/v2"
327 "github.com/knadh/koanf/parsers/json"
328 "github.com/knadh/koanf/providers/file"
329 )
330
331 // Global koanf instance. Use . as the key path delimiter. This can be / or anything.
332 var (
333 k = koanf.New(".")
334 parser = json.Parser()
335 )
336
337 func main() {
338 // Load JSON config.
339 if err := k.Load(file.Provider("mock/mock.json"), parser); err != nil {
340 log.Fatalf("error loading config: %v", err)
341 }
342
343 // Structure to unmarshal nested conf to.
344 type childStruct struct {
345 Name string `koanf:"name"`
346 Type string `koanf:"type"`
347 Empty map[string]string `koanf:"empty"`
348 GrandChild struct {
349 Ids []int `koanf:"ids"`
350 On bool `koanf:"on"`
351 } `koanf:"grandchild1"`
352 }
353
354 var out childStruct
355
356 // Quick unmarshal.
357 k.Unmarshal("parent1.child1", &out)
358 fmt.Println(out)
359
360 // Unmarshal with advanced config.
361 out = childStruct{}
362 k.UnmarshalWithConf("parent1.child1", &out, koanf.UnmarshalConf{Tag: "koanf"})
363 fmt.Println(out)
364
365 // Marshal the instance back to JSON.
366 // The parser instance can be anything, eg: json.Parser(), yaml.Parser() etc.
367 b, _ := k.Marshal(parser)
368 fmt.Println(string(b))
369 }
370 ```
371
372 ### Unmarshalling with flat paths
373
374 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.
375
376 ```go
377 package main
378
379 import (
380 "fmt"
381 "log"
382
383 "github.com/knadh/koanf/v2"
384 "github.com/knadh/koanf/parsers/json"
385 "github.com/knadh/koanf/providers/file"
386 )
387
388 // Global koanf instance. Use . as the key path delimiter. This can be / or anything.
389 var k = koanf.New(".")
390
391 func main() {
392 // Load JSON config.
393 if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil {
394 log.Fatalf("error loading config: %v", err)
395 }
396
397 type rootFlat struct {
398 Type string `koanf:"type"`
399 Empty map[string]string `koanf:"empty"`
400 Parent1Name string `koanf:"parent1.name"`
401 Parent1ID int `koanf:"parent1.id"`
402 Parent1Child1Name string `koanf:"parent1.child1.name"`
403 Parent1Child1Type string `koanf:"parent1.child1.type"`
404 Parent1Child1Empty map[string]string `koanf:"parent1.child1.empty"`
405 Parent1Child1Grandchild1IDs []int `koanf:"parent1.child1.grandchild1.ids"`
406 Parent1Child1Grandchild1On bool `koanf:"parent1.child1.grandchild1.on"`
407 }
408
409 // Unmarshal the whole root with FlatPaths: True.
410 var o1 rootFlat
411 k.UnmarshalWithConf("", &o1, koanf.UnmarshalConf{Tag: "koanf", FlatPaths: true})
412 fmt.Println(o1)
413
414 // Unmarshal a child structure of "parent1".
415 type subFlat struct {
416 Name string `koanf:"name"`
417 ID int `koanf:"id"`
418 Child1Name string `koanf:"child1.name"`
419 Child1Type string `koanf:"child1.type"`
420 Child1Empty map[string]string `koanf:"child1.empty"`
421 Child1Grandchild1IDs []int `koanf:"child1.grandchild1.ids"`
422 Child1Grandchild1On bool `koanf:"child1.grandchild1.on"`
423 }
424
425 var o2 subFlat
426 k.UnmarshalWithConf("parent1", &o2, koanf.UnmarshalConf{Tag: "koanf", FlatPaths: true})
427 fmt.Println(o2)
428 }
429 ```
430
431 #### Reading from nested maps
432
433 The bundled `confmap` provider takes a `map[string]any` that can be loaded into a koanf instance.
434
435 ```go
436 package main
437
438 import (
439 "fmt"
440 "log"
441
442 "github.com/knadh/koanf/v2"
443 "github.com/knadh/koanf/providers/confmap"
444 "github.com/knadh/koanf/providers/file"
445 "github.com/knadh/koanf/parsers/json"
446 "github.com/knadh/koanf/parsers/yaml"
447 )
448
449 // Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character.
450 var k = koanf.New(".")
451
452 func main() {
453 // Load default values using the confmap provider.
454 // We provide a flat map with the "." delimiter.
455 // A nested map can be loaded by setting the delimiter to an empty string "".
456 k.Load(confmap.Provider(map[string]any{
457 "parent1.name": "Default Name",
458 "parent3.name": "New name here",
459 }, "."), nil)
460
461 // Load JSON config on top of the default values.
462 if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil {
463 log.Fatalf("error loading config: %v", err)
464 }
465
466 // Load YAML config and merge into the previously loaded config (because we can).
467 k.Load(file.Provider("mock/mock.yml"), yaml.Parser())
468
469 fmt.Println("parent's name is = ", k.String("parent1.name"))
470 fmt.Println("parent's ID is = ", k.Int("parent1.id"))
471 }
472 ```
473
474 #### Reading from struct
475
476 The bundled `structs` provider can be used to read data from a struct to load into a koanf instance.
477
478 ```go
479 package main
480
481 import (
482 "fmt"
483
484 "github.com/knadh/koanf/v2"
485 "github.com/knadh/koanf/providers/structs"
486 )
487
488 // Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character.
489 var k = koanf.New(".")
490
491 type parentStruct struct {
492 Name string `koanf:"name"`
493 ID int `koanf:"id"`
494 Child1 childStruct `koanf:"child1"`
495 }
496 type childStruct struct {
497 Name string `koanf:"name"`
498 Type string `koanf:"type"`
499 Empty map[string]string `koanf:"empty"`
500 Grandchild1 grandchildStruct `koanf:"grandchild1"`
501 }
502 type grandchildStruct struct {
503 Ids []int `koanf:"ids"`
504 On bool `koanf:"on"`
505 }
506 type sampleStruct struct {
507 Type string `koanf:"type"`
508 Empty map[string]string `koanf:"empty"`
509 Parent1 parentStruct `koanf:"parent1"`
510 }
511
512 func main() {
513 // Load default values using the structs provider.
514 // We provide a struct along with the struct tag `koanf` to the
515 // provider.
516 k.Load(structs.Provider(sampleStruct{
517 Type: "json",
518 Empty: make(map[string]string),
519 Parent1: parentStruct{
520 Name: "parent1",
521 ID: 1234,
522 Child1: childStruct{
523 Name: "child1",
524 Type: "json",
525 Empty: make(map[string]string),
526 Grandchild1: grandchildStruct{
527 Ids: []int{1, 2, 3},
528 On: true,
529 },
530 },
531 },
532 }, "koanf"), nil)
533
534 fmt.Printf("name is = `%s`\n", k.String("parent1.child1.name"))
535 }
536 ```
537 ### Merge behavior
538 #### Default behavior
539 The default behavior when you create Koanf this way is: `koanf.New(delim)` that the latest loaded configuration will
540 merge with the previous one.
541
542 For example:
543 `first.yml`
544 ```yaml
545 key: [1,2,3]
546 ```
547 `second.yml`
548 ```yaml
549 key: 'string'
550 ```
551 When `second.yml` is loaded it will override the type of the `first.yml`.
552
553 If this behavior is not desired, you can merge 'strictly'. In the same scenario, `Load` will return an error.
554
555 ```go
556 package main
557
558 import (
559 "errors"
560 "log"
561
562 "github.com/knadh/koanf/v2"
563 "github.com/knadh/koanf/maps"
564 "github.com/knadh/koanf/parsers/json"
565 "github.com/knadh/koanf/parsers/yaml"
566 "github.com/knadh/koanf/providers/file"
567 )
568
569 var conf = koanf.Conf{
570 Delim: ".",
571 StrictMerge: true,
572 }
573 var k = koanf.NewWithConf(conf)
574
575 func main() {
576 yamlPath := "mock/mock.yml"
577 if err := k.Load(file.Provider(yamlPath), yaml.Parser()); err != nil {
578 log.Fatalf("error loading config: %v", err)
579 }
580
581 jsonPath := "mock/mock.json"
582 if err := k.Load(file.Provider(jsonPath), json.Parser()); err != nil {
583 log.Fatalf("error loading config: %v", err)
584 }
585 }
586 ```
587 **Note:** When merging different extensions, each parser can treat his types differently,
588 meaning even though you the load same types there is a probability that it will fail with `StrictMerge: true`.
589
590 For example: merging JSON and YAML will most likely fail because JSON treats integers as float64 and YAML treats them as integers.
591
592 ### Order of merge and key case sensitivity
593
594 - Config keys are case-sensitive in koanf. For example, `app.server.port` and `APP.SERVER.port` are not the same.
595 - 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.
596
597 ### Custom Providers and Parsers
598
599 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](https://github.com/knadh/koanf/tree/master/providers) and [parsers](https://github.com/knadh/koanf/tree/master/parsers) directories.
600
601 ### Custom merge strategies
602
603 By default, when merging two config sources using `Load()`, koanf recursively merges keys of nested maps (`map[string]any`),
604 while static values are overwritten (slices, strings, etc). This behaviour can be changed by providing a custom merge function with the `WithMergeFunc` option.
605
606 ```go
607 package main
608
609 import (
610 "errors"
611 "log"
612
613 "github.com/knadh/koanf/v2"
614 "github.com/knadh/koanf/maps"
615 "github.com/knadh/koanf/parsers/json"
616 "github.com/knadh/koanf/parsers/yaml"
617 "github.com/knadh/koanf/providers/file"
618 )
619
620 var conf = koanf.Conf{
621 Delim: ".",
622 StrictMerge: true,
623 }
624 var k = koanf.NewWithConf(conf)
625
626 func main() {
627 yamlPath := "mock/mock.yml"
628 if err := k.Load(file.Provider(yamlPath), yaml.Parser()); err != nil {
629 log.Fatalf("error loading config: %v", err)
630 }
631
632 jsonPath := "mock/mock.json"
633 if err := k.Load(file.Provider(jsonPath), json.Parser(), koanf.WithMergeFunc(func(src, dest map[string]any) error {
634 // Your custom logic, copying values from src into dst
635 return nil
636 })); err != nil {
637 log.Fatalf("error loading config: %v", err)
638 }
639 }
640 ```
641
642 ## API
643
644 See the full API documentation of all available methods at https://pkg.go.dev/github.com/knadh/koanf/v2#section-documentation
645
646 ### Bundled Providers
647
648 Install with `go get -u github.com/knadh/koanf/providers/$provider`
649
650 | Package | Provider | Description |
651 | ------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
652 | file | `file.Provider(filepath string)` | Reads a file and returns the raw bytes to be parsed. |
653 | 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. |
654 | basicflag | `basicflag.Provider(f *flag.FlagSet, delim string)` | Takes a stdlib `flag.FlagSet` |
655 | 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. |
656 | 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. |
657 | 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. |
658 | structs | `structs.Provider(s any, tag string)` | Takes a struct and struct tag. |
659 | s3 | `s3.Provider(s3.S3Config{})` | Takes a s3 config struct. |
660 | rawbytes | `rawbytes.Provider(b []byte)` | Takes a raw `[]byte` slice to be parsed with a koanf.Parser |
661 | vault/v2 | `vault.Provider(vault.Config{})` | Hashicorp Vault provider |
662 | appconfig/v2 | `vault.AppConfig(appconfig.Config{})` | AWS AppConfig provider |
663 | etcd/v2 | `etcd.Provider(etcd.Config{})` | CNCF etcd provider |
664 | consul/v2 | `consul.Provider(consul.Config{})` | Hashicorp Consul provider |
665 | parameterstore/v2 | `parameterstore.Provider(parameterstore.Config{})` | AWS Systems Manager Parameter Store provider |
666 | 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. |
667 | 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. |
668 | 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. |
669
670
671 ### Bundled Parsers
672
673 Install with `go get -u github.com/knadh/koanf/parsers/$parser`
674
675 | Package | Parser | Description |
676 | ------------ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
677 | json | `json.Parser()` | Parses JSON bytes into a nested map |
678 | yaml | `yaml.Parser()` | Parses YAML bytes into a nested map |
679 | toml | `toml.Parser()` | Parses TOML bytes into a nested map |
680 | toml/v2 | `toml.Parser()` | Parses TOML bytes into a nested map (using go-toml v2) |
681 | dotenv | `dotenv.Parser()` | Parses DotEnv bytes into a flat map |
682 | hcl | `hcl.Parser(flattenSlices bool)` | Parses Hashicorp HCL bytes into a nested map. `flattenSlices` is recommended to be set to true. [Read more](https://github.com/hashicorp/hcl/issues/162). |
683 | hjson | `hjson.Parser()` | Parses HJSON bytes into a nested map |
684 | huml | `huml.Parser()` | Parses HUML (Human-Oriented Markup Language) bytes into a nested map |
685 | nestedtext | `nestedtext.Parser()` | Parses NestedText bytes into a flat map |
686 |
687
688
689 ### Third-party Providers
690 | Package | Provider | Description |
691 | ------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
692 | github.com/defensestation/koanf/providers/secretsmanager | `vault.SecretsManager(secretsmanager.Config{}, f func(s string) string)` | AWS Secrets Manager provider, takes map or string as a value from store |
693 | github.com/defensestation/koanf/providers/parameterstore | `vault.ParameterStore(parameterstore.Config{}, f func(s string) string)` | AWS ParameterStore provider, an optional function that takes and returns a string to transform env variables |
694
695
696 ### Alternative to viper
697
698 koanf is a [lightweight](https://github.com/knadh/koanf/blob/master/go.mod) alternative to the popular [spf13/viper](https://github.com/spf13/viper). It was written as a result of multiple stumbling blocks encountered with some of viper's fundamental flaws.
699
700 - viper breaks JSON, YAML, TOML, HCL language specs by [forcibly lowercasing keys](https://github.com/spf13/viper/pull/635).
701 - Significantly bloats [build sizes](https://github.com/knadh/koanf/wiki/Comparison-with-spf13-viper).
702 - Tightly couples config parsing with file extensions.
703 - Has poor semantics and abstractions. Commandline, env, file etc. and various parses are hardcoded in the core. There are no primitives that can be extended.
704 - Pulls a large number of [third party dependencies](https://github.com/spf13/viper/issues/707) into the core package. For instance, even if you do not use YAML or flags, the dependencies are still pulled as a result of the coupling.
705 - Imposes arbitrary ordering conventions (eg: flag -> env -> config etc.)
706 - `Get()` returns references to slices and maps. Mutations made outside change the underlying values inside the conf map.
707 - Does non-idiomatic things such as [throwing away O(1) on flat maps](https://github.com/spf13/viper/blob/3b4aca75714a37276c4b1883630bd98c02498b73/viper.go#L1524).
708 - Viper treats keys that contain an empty map (eg: `my_key: {}`) as if they were not set (ie: `IsSet("my_key") == false`).
709 - There are a large number of [open issues](https://github.com/spf13/viper/issues).