-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathwrite.go
65 lines (52 loc) · 1.28 KB
/
write.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
package config
import (
"errors"
"strings"
"github.com/gookit/goutil/maputil"
)
// some common errors definitions
var (
ErrReadonly = errors.New("the config instance in 'readonly' mode")
ErrKeyIsEmpty = errors.New("the config key is cannot be empty")
ErrNotFound = errors.New("this key does not exist in the config")
)
// SetData for override the Config.Data
func SetData(data map[string]any) {
dc.SetData(data)
}
// SetData for override the Config.Data
func (c *Config) SetData(data map[string]any) {
c.lock.Lock()
c.data = data
c.lock.Unlock()
c.fireHook(OnSetData)
}
// Set val by key
func Set(key string, val any, setByPath ...bool) error {
return dc.Set(key, val, setByPath...)
}
// Set a value by key string.
func (c *Config) Set(key string, val any, setByPath ...bool) (err error) {
if c.opts.Readonly {
return ErrReadonly
}
c.lock.Lock()
defer c.lock.Unlock()
sep := c.opts.Delimiter
if key = formatKey(key, string(sep)); key == "" {
return ErrKeyIsEmpty
}
defer c.fireHook(OnSetValue)
if strings.IndexByte(key, sep) == -1 {
c.data[key] = val
return
}
// disable set by path.
if len(setByPath) > 0 && !setByPath[0] {
c.data[key] = val
return
}
// set by path
keys := strings.Split(key, string(sep))
return maputil.SetByKeys(&c.data, keys, val)
}