/
koanf_confmap.go
69 lines (59 loc) · 1.75 KB
/
koanf_confmap.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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package configx
import (
"bytes"
"encoding/json"
"errors"
"github.com/knadh/koanf/maps"
"github.com/tidwall/gjson"
)
// KoanfConfmap implements a raw map[string]interface{} provider.
type KoanfConfmap struct {
tuples []tuple
}
// Provider returns a confmap Provider that takes a flat or nested
// map[string]interface{}. If a delim is provided, it indicates that the
// keys are flat and the map needs to be unflatted by delim.
func NewKoanfConfmap(tuples []tuple) *KoanfConfmap {
return &KoanfConfmap{tuples: jsonify(tuples)}
}
func jsonify(tuples []tuple) []tuple {
for k, t := range tuples {
var parsed interface{}
switch vt := t.Value.(type) {
case string:
if gjson.Valid(vt) && json.NewDecoder(bytes.NewBufferString(vt)).Decode(&parsed) == nil {
tuples[k].Value = parsed
}
continue
case []byte:
if gjson.ValidBytes(vt) && json.NewDecoder(bytes.NewBuffer(vt)).Decode(&parsed) == nil {
tuples[k].Value = parsed
}
continue
case json.RawMessage:
if gjson.ValidBytes(vt) && json.NewDecoder(bytes.NewBuffer(vt)).Decode(&parsed) == nil {
tuples[k].Value = parsed
}
continue
}
}
return tuples
}
// ReadBytes is not supported by the env provider.
func (e *KoanfConfmap) ReadBytes() ([]byte, error) {
return nil, errors.New("confmap provider does not support this method")
}
// Read returns the loaded map[string]interface{}.
func (e *KoanfConfmap) Read() (map[string]interface{}, error) {
values := map[string]interface{}{}
for _, t := range e.tuples {
values[t.Key] = t.Value
}
// Ensure any nested values are properly converted as well
cp := maps.Copy(values)
maps.IntfaceKeysToStrings(cp)
cp = maps.Unflatten(cp, Delimiter)
return cp, nil
}