-
Notifications
You must be signed in to change notification settings - Fork 8
/
resolver.go
123 lines (114 loc) · 2.67 KB
/
resolver.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/**
* @Time: 2022/2/23 10:02
* @Author: yt.yin
*/
package goconfig
import (
"github.com/fsnotify/fsnotify"
"github.com/goworkeryyt/go-config/env"
"github.com/spf13/viper"
"log"
"sync"
)
var (
// 全局配置
globalConfig *Config
// 为该全局变量创建一个锁
glcMutex sync.Mutex
)
const (
// ConfigSuffix 配置文件默认后缀
ConfigSuffix = "_config"
// ConfigType 配置文件类型
ConfigType = "yaml"
// ConfigPath 配置文件所在路径
ConfigPath = "./resources"
)
// SubItem 从配置中获取指定的配置子项
func (c *Config) SubItem(subKey string, v interface{}) {
glcMutex.Lock()
defer glcMutex.Unlock()
if globalConfig == nil || globalConfig.Viper == nil {
active := env.Active()
filename := active.Value() + ConfigSuffix
v := viper.New()
v.SetConfigName(filename)
v.SetConfigType(ConfigType)
v.AddConfigPath(ConfigPath)
log.Println("读取配置文件:", filename)
err := v.ReadInConfig()
if err != nil {
log.Fatalf("读取配置文件异常 : %s \n", err)
return
}
globalConfig = &Config{}
if err := v.Unmarshal(globalConfig); err != nil {
log.Fatalf("读取配置文件异常 : %s \n", err)
return
}
if globalConfig != nil && globalConfig.Viper != nil {
globalConfig.Viper = v
}
// 获取子项的值
value := v.Sub(subKey)
if value == nil {
return
}
err = value.Unmarshal(v)
if err != nil {
log.Fatalf("读取子配置项异常 : %s \n", err)
}
return
}
value := globalConfig.Viper.Sub(subKey)
if value == nil {
return
}
err := value.Unmarshal(v)
if err != nil {
log.Println("读取子配置项异常:", err)
}
return
}
// GlobalConfig 获取全局配置
func GlobalConfig(envArr ...string) *Config {
glcMutex.Lock()
defer glcMutex.Unlock()
if globalConfig != nil {
return globalConfig
}
v := viper.New()
filename := ""
if len(envArr) == 0 {
active := env.Active()
filename = active.Value() + ConfigSuffix
} else {
filename = envArr[0] + ConfigSuffix
}
v.SetConfigName(filename)
v.SetConfigType(ConfigType)
v.AddConfigPath(ConfigPath)
log.Println("读取配置文件:", filename)
err := v.ReadInConfig()
if err != nil {
log.Fatalf("读取配置文件异常 : %s \n", err)
return nil
}
globalConfig = &Config{}
if err := v.Unmarshal(globalConfig); err != nil {
log.Fatalf("读取配置文件异常 : %s \n", err)
return nil
}
globalConfig.Viper = v
// 监控配置改变
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
log.Println("配置文件内容发生改变:", e.Name)
if err := v.Unmarshal(globalConfig); err != nil {
log.Fatalf("读取配置文件异常 : %s \n", err)
return
}
globalConfig.Viper = v
})
return globalConfig
}