forked from zlyuancn/zconn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
viper.go
80 lines (69 loc) · 1.8 KB
/
viper.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
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/6/6
Description :
-------------------------------------------------
*/
package zconn
import (
"fmt"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
)
const ConfigShardName = "zconn"
type viperConfig map[ConnType]map[string]interface{}
// 添加配置文件, 支持 json, ini, toml, yaml等
//
// toml示例:
// [zconn.es7.default]
// address=['http://127.0.0.1:9200']
// username='your_user'
// password='your_pwd'
//
func (m *Manager) AddFile(file string, filetype ...string) error {
v := viper.New()
v.SetConfigFile(file)
if len(filetype) > 0 {
v.SetConfigType(filetype[0])
}
if err := v.ReadInConfig(); err != nil {
return err
}
return m.AddViperTree(v)
}
// 添加viper树
func (m *Manager) AddViperTree(tree *viper.Viper) error {
vconf := make(viperConfig)
err := tree.UnmarshalKey(ConfigShardName, &vconf)
if err != nil {
return fmt.Errorf("tree解析失败: %s", err.Error())
}
for conn_type, conns := range vconf {
for name, raw_conf := range conns {
conf := mustGetConnector(conn_type).NewEmptyConfig()
conf_ptr := makeConfigPtr(conf)
err = decodeRawConfig(raw_conf, conf_ptr)
if err != nil {
return fmt.Errorf("配置解析失败: %s.%s: %s", conn_type, name, err.Error())
}
m.AddConfig(conn_type, conf_ptr, name)
}
}
return nil
}
func decodeRawConfig(raw interface{}, config interface{}) error {
c := &mapstructure.DecoderConfig{
Result: config,
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
),
}
decoder, err := mapstructure.NewDecoder(c)
if err != nil {
return err
}
return decoder.Decode(raw)
}