/
config.go
66 lines (59 loc) · 1.34 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
package cfg
import (
jsoniter "github.com/json-iterator/go"
"github.com/spf13/viper"
"go.uber.org/zap"
)
type Manager struct {
*viper.Viper
datasource DataSource
}
func (m *Manager) GetDatasource() DataSource {
if m == nil {
return DataSource{}
}
return m.datasource
}
type configType string
const (
configTypeDatasource configType = "datasource"
)
func NewManager(options ...Option) *Manager {
opt := NewDefaultOption()
if len(options) > 0 {
opt = options[0]
}
path := opt.Path
m := Manager{
Viper: viper.New(),
datasource: DataSource{},
}
zap.L().Sugar().Infof("cfg path=%s", opt.Path)
reader := viper.New()
reader.AddConfigPath(path)
reader.SetConfigType(string(opt.FileType))
if opt.NeedDatasource {
opt.ConfigList = append(opt.ConfigList, string(configTypeDatasource))
}
for _, key := range opt.ConfigList {
zap.L().Sugar().Infof("load cfg from %s", key)
reader.SetConfigName(key)
err := reader.ReadInConfig()
if err != nil {
zap.S().Errorf("load cfg from %s failed: %s", key, err)
}
conf := map[string]interface{}{}
if reader.IsSet(key) {
conf[key] = reader.Get(key)
} else {
conf[key] = reader.AllSettings()
}
switch key {
case string(configTypeDatasource):
b, _ := jsoniter.Marshal(conf[key])
_ = jsoniter.Unmarshal(b, &m.datasource)
}
m.Viper.Set(key, conf[key])
}
return &m
}