forked from miracl/conflate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (81 loc) · 2.23 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Package main demonstrates a sample conflate usage.
package main
import (
"fmt"
"path"
"runtime"
"github.com/miracl/conflate"
)
// example of a custom unmarshaller for JSON.
func customJSONUnmarshal(data []byte, out interface{}) error {
fmt.Println("Using custom JSON Unmarshaller")
return conflate.JSONUnmarshal(data, out)
}
func main() {
// define the unmarshallers for the given file extensions, blank extension is the global unmarshaller
conflate.Unmarshallers = conflate.UnmarshallerMap{
".json": conflate.UnmarshallerFuncs{customJSONUnmarshal},
".jsn": conflate.UnmarshallerFuncs{conflate.JSONUnmarshal},
".yaml": conflate.UnmarshallerFuncs{conflate.YAMLUnmarshal},
".yml": conflate.UnmarshallerFuncs{conflate.YAMLUnmarshal},
".toml": conflate.UnmarshallerFuncs{conflate.TOMLUnmarshal},
".tml": conflate.UnmarshallerFuncs{conflate.TOMLUnmarshal},
"": conflate.UnmarshallerFuncs{conflate.JSONUnmarshal, conflate.YAMLUnmarshal, conflate.TOMLUnmarshal},
}
_, thisFile, _, _ := runtime.Caller(0) //nolint:dogsled // ok for an example
thisDir := path.Dir(thisFile)
// merge multiple config files
c, err := conflate.FromFiles(path.Join(thisDir, "../testdata/valid_parent.json"))
if err != nil {
fmt.Println(err)
return
}
// load a json schema
schema, err := conflate.NewSchemaFile(path.Join(thisDir, "../testdata/test.schema.json"))
if err != nil {
fmt.Println(err)
return
}
// apply defaults defined in schema to merged data
err = c.ApplyDefaults(schema)
if err != nil {
fmt.Println(err)
return
}
// validate merged data against schema
err = c.Validate(schema)
if err != nil {
fmt.Println(err)
return
}
// unmarshal merged data to a struct/interface
var data interface{}
err = c.Unmarshal(&data)
if err != nil {
fmt.Println(err)
return
}
// output merged data as json
json, err := c.MarshalJSON()
if err != nil {
fmt.Println(err)
return
}
// output merged data as yaml
yaml, err := c.MarshalYAML()
if err != nil {
fmt.Println(err)
return
}
// output merged data as toml
toml, err := c.MarshalTOML()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(json))
fmt.Println("")
fmt.Println(string(yaml))
fmt.Println("")
fmt.Println(string(toml))
}