| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
|
| 7 |
"github.com/knadh/koanf/parsers/json" |
| 8 |
"github.com/knadh/koanf/parsers/yaml" |
| 9 |
"github.com/knadh/koanf/providers/confmap" |
| 10 |
"github.com/knadh/koanf/providers/file" |
| 11 |
"github.com/knadh/koanf/v2" |
| 12 |
) |
| 13 |
|
| 14 |
// Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character. |
| 15 |
var k = koanf.New(".") |
| 16 |
|
| 17 |
func main() { |
| 18 |
// Load default values using the confmap provider. |
| 19 |
// We provide a flat map with the "." delimiter. |
| 20 |
// A nested map can be loaded by setting the delimiter to an empty string "". |
| 21 |
k.Load(confmap.Provider(map[string]any{ |
| 22 |
"parent1.name": "Default Name", |
| 23 |
"parent3.name": "New name here", |
| 24 |
}, "."), nil) |
| 25 |
|
| 26 |
// Load JSON config on top of the default values. |
| 27 |
if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil { |
| 28 |
log.Fatalf("error loading config: %v", err) |
| 29 |
} |
| 30 |
|
| 31 |
// Load YAML config and merge into the previously loaded config (because we can). |
| 32 |
k.Load(file.Provider("mock/mock.yml"), yaml.Parser()) |
| 33 |
|
| 34 |
fmt.Println("parent's name is = ", k.String("parent1.name")) |
| 35 |
fmt.Println("parent's ID is = ", k.Int("parent1.id")) |
| 36 |
} |