-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyaml.go
50 lines (40 loc) · 1.04 KB
/
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
// Package yaml provides a YAML loader for xload.
package yaml
import (
"io"
"os"
"gopkg.in/yaml.v3"
"github.com/gojekfarm/xtools/xload"
)
// NewFileLoader reads YAML from the given file and returns a xload.Loader
// Nested keys are flattened using the given separator.
//
// IMPORTANT: The separator must be consistent with prefix used in the struct
// tags.
func NewFileLoader(path, sep string) (_ xload.MapLoader, err error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() {
err = f.Close()
}()
return NewLoader(f, sep)
}
// NewLoader reads YAML from the given io.Reader and returns a xload.Loader
// Nested keys are flattened using the given separator.
//
// IMPORTANT: The separator must be consistent with prefix used in the struct
// tags.
func NewLoader(r io.Reader, sep string) (xload.MapLoader, error) {
b, err := io.ReadAll(r)
if err != nil {
return nil, err
}
var out map[string]interface{}
err = yaml.Unmarshal(b, &out)
if err != nil {
return nil, err
}
return xload.FlattenMap(out, sep), nil
}