-
Notifications
You must be signed in to change notification settings - Fork 0
/
yaml.go
51 lines (42 loc) · 831 Bytes
/
yaml.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
package cfgloader
import (
"encoding/json"
"io"
"os"
"github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v3"
)
func LoadYAML(in []byte, out interface{}, schema []byte) error {
if err := yaml.Unmarshal(in, out); err != nil {
return err
}
if schema != nil {
outJSON, err := json.Marshal(out)
if err != nil {
return err
}
res, err := gojsonschema.Validate(
gojsonschema.NewBytesLoader(schema),
gojsonschema.NewBytesLoader(outJSON),
)
if err != nil {
return err
}
if !res.Valid() {
return SchemaValidationError{Result: res}
}
}
return nil
}
func LoadYAMLFromPath(path string, out interface{}, schema []byte) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
return LoadYAML(b, out, schema)
}