-
Notifications
You must be signed in to change notification settings - Fork 170
/
proxies.go
103 lines (87 loc) · 1.99 KB
/
proxies.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
package config
import (
"strings"
"sync"
"github.com/pydio/cells/v4/common/utils/configx"
)
type ProxySetter func(Store, interface{}, ...string) error
type ProxyGetter func(Store, ...string) configx.Values
type ProxyDeleter func(Store, ...string) error
var (
proxiesSetters = map[string]ProxySetter{}
proxiesGetters = map[string]ProxyGetter{}
proxiesDeleters = map[string]ProxyDeleter{}
proxiesLocker *sync.RWMutex
)
func init() {
proxiesLocker = &sync.RWMutex{}
}
func RegisterProxy(key string, interceptors ...interface{}) {
proxiesLocker.Lock()
defer proxiesLocker.Unlock()
for _, interceptor := range interceptors {
switch v := interceptor.(type) {
case ProxySetter:
proxiesSetters[key] = v
case ProxyGetter:
proxiesGetters[key] = v
case ProxyDeleter:
proxiesDeleters[key] = v
}
}
}
type proxy struct {
Store
}
type proxyValues struct {
configx.Values
setter ProxySetter
getter ProxyGetter
deleter ProxyDeleter
store Store
path []string
}
func Proxy(store Store) Store {
return &proxy{Store: store}
}
func (p *proxy) Val(path ...string) configx.Values {
key := strings.Join(path, "/")
wrapped := false
pVal := &proxyValues{Values: p.Store.Val(path...), store: p.Store, path: path}
proxiesLocker.RLock()
defer proxiesLocker.RUnlock()
if setter, ok := proxiesSetters[key]; ok {
pVal.setter = setter
wrapped = true
}
if getter, ok := proxiesGetters[key]; ok {
pVal.getter = getter
wrapped = true
}
if deleter, ok := proxiesDeleters[key]; ok {
pVal.deleter = deleter
wrapped = true
}
if wrapped {
return pVal
}
return p.Store.Val(path...)
}
func (p *proxyValues) Set(val interface{}) error {
if p.setter != nil {
return p.setter(p.store, val, p.path...)
}
return p.Values.Set(val)
}
func (p *proxyValues) Get() configx.Value {
if p.getter != nil {
return p.getter(p.store, p.path...)
}
return p.Values.Get()
}
func (p *proxyValues) Del() error {
if p.deleter != nil {
return p.deleter(p.store, p.path...)
}
return p.Values.Del()
}