| 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/file" |
| 10 |
"github.com/knadh/koanf/v2" |
| 11 |
) |
| 12 |
|
| 13 |
// Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character. |
| 14 |
var k = koanf.New(".") |
| 15 |
|
| 16 |
func main() { |
| 17 |
// Load JSON config. |
| 18 |
f := file.Provider("mock/mock.json") |
| 19 |
if err := k.Load(f, json.Parser()); err != nil { |
| 20 |
log.Fatalf("error loading config: %v", err) |
| 21 |
} |
| 22 |
|
| 23 |
// Load YAML config and merge into the previously loaded config (because we can). |
| 24 |
k.Load(file.Provider("mock/mock.yml"), yaml.Parser()) |
| 25 |
|
| 26 |
fmt.Println("parent's name is = ", k.String("parent1.name")) |
| 27 |
fmt.Println("parent's ID is = ", k.Int("parent1.id")) |
| 28 |
|
| 29 |
// Watch the file and get a callback on change. The callback can do whatever, |
| 30 |
// like re-load the configuration. |
| 31 |
// File provider always returns a nil `event`. |
| 32 |
f.Watch(func(event any, err error) { |
| 33 |
if err != nil { |
| 34 |
log.Printf("watch error: %v", err) |
| 35 |
return |
| 36 |
} |
| 37 |
|
| 38 |
log.Println("config changed. Reloading ...") |
| 39 |
k.Load(f, json.Parser()) |
| 40 |
k.Print() |
| 41 |
}) |
| 42 |
|
| 43 |
// Block forever (and manually make a change to mock/mock.json) to |
| 44 |
// reload the config. |
| 45 |
log.Println("waiting forever. Try making a change to mock/mock.json to live reload") |
| 46 |
<-make(chan bool) |
| 47 |
} |