| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
|
| 6 |
"github.com/knadh/koanf/providers/structs" |
| 7 |
"github.com/knadh/koanf/v2" |
| 8 |
) |
| 9 |
|
| 10 |
var k = koanf.New(".") |
| 11 |
|
| 12 |
type parentStruct struct { |
| 13 |
Name string `koanf:"name"` |
| 14 |
ID int `koanf:"id"` |
| 15 |
Child1 childStruct `koanf:"child1"` |
| 16 |
} |
| 17 |
type childStruct struct { |
| 18 |
Name string `koanf:"name"` |
| 19 |
Type string `koanf:"type"` |
| 20 |
Empty map[string]string `koanf:"empty"` |
| 21 |
Grandchild1 grandchildStruct `koanf:"grandchild1"` |
| 22 |
} |
| 23 |
type grandchildStruct struct { |
| 24 |
Ids []int `koanf:"ids"` |
| 25 |
On bool `koanf:"on"` |
| 26 |
} |
| 27 |
type sampleStruct struct { |
| 28 |
Type string `koanf:"type"` |
| 29 |
Empty map[string]string `koanf:"empty"` |
| 30 |
Parent1 parentStruct `koanf:"parent1"` |
| 31 |
} |
| 32 |
|
| 33 |
func main() { |
| 34 |
s := sampleStruct{ |
| 35 |
Type: "json", |
| 36 |
Empty: make(map[string]string), |
| 37 |
Parent1: parentStruct{ |
| 38 |
Name: "parent1", |
| 39 |
ID: 1234, |
| 40 |
Child1: childStruct{ |
| 41 |
Name: "child1", |
| 42 |
Type: "json", |
| 43 |
Empty: make(map[string]string), |
| 44 |
Grandchild1: grandchildStruct{ |
| 45 |
Ids: []int{1, 2, 3}, |
| 46 |
On: true, |
| 47 |
}, |
| 48 |
}, |
| 49 |
}, |
| 50 |
} |
| 51 |
|
| 52 |
k.Load(structs.Provider(s, "koanf"), nil) |
| 53 |
|
| 54 |
fmt.Printf("name is = `%s`\n", k.String("parent1.child1.name")) |
| 55 |
} |