-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader_decorator_alter_value.go
66 lines (55 loc) · 1.74 KB
/
loader_decorator_alter_value.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
// Copyright The ActForGood Authors.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://github.com/actforgood/xconf/blob/main/LICENSE.
package xconf
import (
"strings"
"github.com/spf13/cast"
)
// AlterValueFunc is a function that manipulates a config's value.
type AlterValueFunc func(value any) any
// AlterValueLoader decorates another loader to manipulate a config's value.
// The transformation function is applied to all passed keys.
func AlterValueLoader(loader Loader, transformation AlterValueFunc, keys ...string) Loader {
return LoaderFunc(func() (map[string]any, error) {
configMap, err := loader.Load()
if err != nil {
return configMap, err
}
for _, key := range keys {
if value, found := configMap[key]; found {
configMap[key] = transformation(value)
}
}
return configMap, nil
})
}
// ToStringList makes a slice of strings from a string value,
// who's items are separated by given separator parameter.
//
// If the original value is not a string, the value remains unaltered.
//
// Example: "bread,eggs,milk" => ["bread", "eggs", "milk"].
func ToStringList(sep string) AlterValueFunc {
return func(value any) any {
if strValue, ok := value.(string); ok {
return strings.Split(strValue, sep)
}
return value
}
}
// ToIntList makes a slice of integers from a string value,
// who's items are separated by given separator parameter.
//
// If the original value is not a string, the value remains unaltered.
//
// Example: "10,100,1000" => [10, 100, 1000].
func ToIntList(sep string) AlterValueFunc {
return func(value any) any {
if strValue, ok := value.(string); ok {
return cast.ToIntSlice(strings.Split(strValue, sep))
}
return value
}
}