| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
|
| 7 |
"github.com/knadh/koanf/parsers/json" |
| 8 |
"github.com/knadh/koanf/providers/file" |
| 9 |
"github.com/knadh/koanf/v2" |
| 10 |
) |
| 11 |
|
| 12 |
// Global koanf instance. Use . as the key path delimiter. This can be / or anything. |
| 13 |
var k = koanf.New(".") |
| 14 |
|
| 15 |
func main() { |
| 16 |
// Load JSON config. |
| 17 |
if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil { |
| 18 |
log.Fatalf("error loading config: %v", err) |
| 19 |
} |
| 20 |
|
| 21 |
type rootFlat struct { |
| 22 |
Type string `koanf:"type"` |
| 23 |
Empty map[string]string `koanf:"empty"` |
| 24 |
Parent1Name string `koanf:"parent1.name"` |
| 25 |
Parent1ID int `koanf:"parent1.id"` |
| 26 |
Parent1Child1Name string `koanf:"parent1.child1.name"` |
| 27 |
Parent1Child1Type string `koanf:"parent1.child1.type"` |
| 28 |
Parent1Child1Empty map[string]string `koanf:"parent1.child1.empty"` |
| 29 |
Parent1Child1Grandchild1IDs []int `koanf:"parent1.child1.grandchild1.ids"` |
| 30 |
Parent1Child1Grandchild1On bool `koanf:"parent1.child1.grandchild1.on"` |
| 31 |
} |
| 32 |
|
| 33 |
// Unmarshal the whole root with FlatPaths: True. |
| 34 |
var o1 rootFlat |
| 35 |
k.UnmarshalWithConf("", &o1, koanf.UnmarshalConf{Tag: "koanf", FlatPaths: true}) |
| 36 |
fmt.Println(o1) |
| 37 |
|
| 38 |
// Unmarshal a child structure of "parent1". |
| 39 |
type subFlat struct { |
| 40 |
Name string `koanf:"name"` |
| 41 |
ID int `koanf:"id"` |
| 42 |
Child1Name string `koanf:"child1.name"` |
| 43 |
Child1Type string `koanf:"child1.type"` |
| 44 |
Child1Empty map[string]string `koanf:"child1.empty"` |
| 45 |
Child1Grandchild1IDs []int `koanf:"child1.grandchild1.ids"` |
| 46 |
Child1Grandchild1On bool `koanf:"child1.grandchild1.on"` |
| 47 |
} |
| 48 |
|
| 49 |
var o2 subFlat |
| 50 |
k.UnmarshalWithConf("parent1", &o2, koanf.UnmarshalConf{Tag: "koanf", FlatPaths: true}) |
| 51 |
fmt.Println(o2) |
| 52 |
} |