-
Notifications
You must be signed in to change notification settings - Fork 331
/
init.go
69 lines (57 loc) · 1.44 KB
/
init.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
package conf
import (
"fmt"
//"path/filepath"
"os"
//"runtime"
"github.com/spf13/viper"
)
var Handler *viper.Viper
var HandlerInfo *viper.Viper
var newConfs map[string]*viper.Viper
// Root current dir
var Root string
func Init(confPath string) {
var err error
newConfs = make(map[string]*viper.Viper)
//_, fn, _, _ := runtime.Caller(0)
//Root = filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(fn))))
Root, err = os.Getwd()
if err != nil {
panic(fmt.Errorf("Initialize Root error: %s", err))
}
Handler = LoadConfig(confPath)
HandlerInfo = LoadConfig(Root + "/conf/info.toml")
}
func LoadConfig(confPath string) *viper.Viper {
handler := viper.New()
if confPath == "" {
handler.SetConfigName("app") // 默认文件配置文件为app.toml
handler.AddConfigPath(Root + "/conf")
} else {
handler.SetConfigFile(confPath)
}
err := handler.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %s", err))
}
return handler
}
// FreshHandler 从磁盘读取配置文件,方便本地修改配置的测试,无需重启服务
func FreshHandler() {
Handler.ReadInConfig()
HandlerInfo.ReadInConfig()
}
// NewConf 实例化读取配置文件
func NewConf(confFile string) *viper.Viper {
if obj, ok := newConfs[confFile]; ok {
obj.ReadInConfig()
return obj
} else {
viperObj := viper.New()
viperObj.SetConfigFile(confFile)
newConfs[confFile] = viperObj
viperObj.ReadInConfig()
return viperObj
}
}