| 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 ( |
| 14 |
k = koanf.New(".") |
| 15 |
parser = json.Parser() |
| 16 |
) |
| 17 |
|
| 18 |
func main() { |
| 19 |
// Load JSON config. |
| 20 |
if err := k.Load(file.Provider("mock/mock.json"), parser); err != nil { |
| 21 |
log.Fatalf("error loading config: %v", err) |
| 22 |
} |
| 23 |
|
| 24 |
// Structure to unmarshal nested conf to. |
| 25 |
type childStruct struct { |
| 26 |
Name string `koanf:"name"` |
| 27 |
Type string `koanf:"type"` |
| 28 |
Empty map[string]string `koanf:"empty"` |
| 29 |
GrandChild struct { |
| 30 |
Ids []int `koanf:"ids"` |
| 31 |
On bool `koanf:"on"` |
| 32 |
} `koanf:"grandchild1"` |
| 33 |
} |
| 34 |
|
| 35 |
var out childStruct |
| 36 |
|
| 37 |
// Quick unmarshal. |
| 38 |
k.Unmarshal("parent1.child1", &out) |
| 39 |
fmt.Println(out) |
| 40 |
|
| 41 |
// Unmarshal with advanced config. |
| 42 |
out = childStruct{} |
| 43 |
k.UnmarshalWithConf("parent1.child1", &out, koanf.UnmarshalConf{Tag: "koanf"}) |
| 44 |
fmt.Println(out) |
| 45 |
|
| 46 |
// Marshal the instance back to JSON. |
| 47 |
// The parser instance can be anything, eg: json.Parser(), |
| 48 |
// yaml.Parser() etc. |
| 49 |
b, _ := k.Marshal(parser) |
| 50 |
fmt.Println(string(b)) |
| 51 |
} |