/
parser.go
77 lines (62 loc) · 1.73 KB
/
parser.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
package configuration
import (
"encoding/json"
"strings"
"github.com/spf13/cast"
"gopkg.in/yaml.v2"
)
func mapToLowerKeys(m map[string]interface{}) {
for key, val := range m {
switch val.(type) {
case map[string]interface{}:
// nested map: call recursively
mapToLowerKeys(val.(map[string]interface{}))
case map[interface{}]interface{}:
// nested map: cast and call recursively
val = cast.ToStringMap(val)
mapToLowerKeys(val.(map[string]interface{}))
}
lower := strings.ToLower(key)
if key != lower {
// remove old key (not lower-cased)
delete(m, key)
}
// update map
m[lower] = val
}
}
// JSONLowerParser implements a JSON parser.
// all config keys are lower cased.
type JSONLowerParser struct {
prefix string
indent string
}
// Unmarshal parses the given JSON bytes.
func (p *JSONLowerParser) Unmarshal(b []byte) (map[string]interface{}, error) {
var out map[string]interface{}
if err := json.Unmarshal(b, &out); err != nil {
return nil, err
}
mapToLowerKeys(out)
return out, nil
}
// Marshal marshals the given config map to JSON bytes.
func (p *JSONLowerParser) Marshal(o map[string]interface{}) ([]byte, error) {
return json.MarshalIndent(o, p.prefix, p.indent)
}
// YAMLLowerParser implements a YAML parser.
// all config keys are lower cased.
type YAMLLowerParser struct{}
// Unmarshal parses the given YAML bytes.
func (p *YAMLLowerParser) Unmarshal(b []byte) (map[string]interface{}, error) {
var out map[string]interface{}
if err := yaml.Unmarshal(b, &out); err != nil {
return nil, err
}
mapToLowerKeys(out)
return out, nil
}
// Marshal marshals the given config map to YAML bytes.
func (p *YAMLLowerParser) Marshal(o map[string]interface{}) ([]byte, error) {
return yaml.Marshal(o)
}