-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetting.go
114 lines (87 loc) · 2.19 KB
/
setting.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package kareless
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
"github.com/spf13/cast"
)
type SettingSource interface {
Get(ctx context.Context, key string) (any, error)
}
const SettingKeyDelimiter = "."
func IsSettingRootKey(key string) bool {
return len(strings.TrimSpace(key)) == 0 || key == "."
}
type Settings struct {
lock sync.RWMutex
rr []SettingSource
}
func (ss *Settings) Prepend(source SettingSource) {
ss.lock.Lock()
defer ss.lock.Unlock()
ss.rr = append([]SettingSource{source}, ss.rr...)
}
func (ss *Settings) Append(source SettingSource) {
ss.lock.Lock()
defer ss.lock.Unlock()
ss.rr = append(ss.rr, source)
}
func (ss *Settings) get(ctx context.Context, key string) any {
ss.lock.RLock()
defer ss.lock.RUnlock()
for _, r := range ss.rr {
v, err := r.Get(ctx, key)
if err == nil && v != nil {
return v
}
}
return nil
}
func (ss *Settings) UnmarshalJson(key string, valPtr any) error {
bb, err := json.Marshal(ss.get(context.Background(), key))
if err != nil {
return err
}
return json.Unmarshal(bb, valPtr)
}
func (ss *Settings) GetString(key string) string {
return cast.ToString(ss.get(context.Background(), key))
}
func (ss *Settings) GetStringSlice(key string) []string {
return cast.ToStringSlice(ss.get(context.Background(), key))
}
func (ss *Settings) GetInt(key string) int {
return cast.ToInt(ss.get(context.Background(), key))
}
func (ss *Settings) GetInt64(key string) int64 {
return cast.ToInt64(ss.get(context.Background(), key))
}
func (ss *Settings) GetByte(key string) byte {
return byte(ss.GetInt(key))
}
func (ss *Settings) GetBool(key string) bool {
return cast.ToBool(ss.get(context.Background(), key))
}
func (ss *Settings) GetDuration(key string) time.Duration {
return cast.ToDuration(ss.get(context.Background(), key))
}
func (ss *Settings) Children(key string) []string {
v := ss.get(context.Background(), key)
if aa, err := cast.ToSliceE(v); err == nil {
kk := make([]string, len(aa))
for k := range aa {
kk[k] = cast.ToString(k)
}
return kk
}
if aa, err := cast.ToStringMapE(v); err == nil {
kk := make([]string, 0, len(aa))
for k := range aa {
kk = append(kk, k)
}
return kk
}
return nil
}