-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
109 lines (88 loc) · 2.08 KB
/
config.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
package config
import (
"sync"
"time"
"github.com/MQEnergy/go-skeleton/pkg/cache/smap"
"github.com/spf13/cast"
)
var ConfEnv string
// CommonInterface ...
type CommonInterface interface {
Get(key string) any
Set(key string, value any) bool
Has(key string) bool
}
type Config struct {
viper CommonInterface
cache CacheInterface
mu *sync.Mutex
}
var _ Interface = (*Config)(nil)
// ============================= Config Cache ====================================
func New(config CommonInterface, option Options) (provider *Config, err error) {
if option.Cache == nil {
option.Cache = smap.New()
}
if option.CachePrefix == "" {
option.CachePrefix = "config"
}
if option.Ctype == "" {
option.Ctype = "yaml"
}
if d, ok := config.(interface {
Apply(Options) error
}); ok {
if err = d.Apply(option); err != nil {
return
}
}
return &Config{
viper: config,
cache: option.Cache,
mu: &sync.Mutex{},
}, nil
}
func (c *Config) _cache(key string, value any) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.cache.Has(key) {
return true
}
return c.cache.Set(key, value)
}
func (c *Config) Get(key string) any {
if c.cache.Has(key) {
return c.cache.Get(key)
}
val := c.viper.Get(key)
c._cache(key, val)
return val
}
func (c *Config) GetString(key string) string {
return cast.ToString(c.Get(key))
}
func (c *Config) GetBool(key string) bool {
return cast.ToBool(c.Get(key))
}
func (c *Config) GetInt(key string) int {
return cast.ToInt(c.Get(key))
}
func (c *Config) GetInt32(key string) int32 {
return cast.ToInt32(c.Get(key))
}
func (c *Config) GetInt64(key string) int64 {
return cast.ToInt64(c.Get(key))
}
func (c *Config) GetFloat64(key string) float64 {
return cast.ToFloat64(c.Get(key))
}
func (c *Config) GetDuration(key string) time.Duration {
return cast.ToDuration(c.Get(key))
}
func (c *Config) GetStringSlice(key string) []string {
return cast.ToStringSlice(c.Get(key))
}
func (c *Config) GetStringMap(key string) map[string]any {
return cast.ToStringMap(c.Get(key))
}
// ============================= Config Cache ====================================