-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
71 lines (62 loc) · 1.45 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
package common
import (
"fmt"
"os"
"path"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"github.com/wwqdrh/gokit/basetool/datax"
"github.com/wwqdrh/gokit/logger"
)
// filepath ext
func InitConfig(file, ext string, config interface{}, withdefault bool, init func(interface{}) error) error {
v := viper.New()
if file, err := getConfigWithMode(file); err != nil {
logger.DefaultLogger.Warn("config file not exsit")
if withdefault {
datax.LoadDefault(config)
}
} else {
v.SetConfigFile(file)
v.SetConfigType(ext)
err := v.ReadInConfig()
if err != nil {
return fmt.Errorf("fatal error config file: %w", err)
}
v.WatchConfig()
v.OnConfigChange(func(in fsnotify.Event) {
if err := v.Unmarshal(config); err != nil {
fmt.Println(err)
return
}
if withdefault {
datax.LoadDefault(config)
}
if err := init(config); err != nil {
logger.DefaultLogger.Error(err.Error())
}
})
if err := v.Unmarshal(config); err != nil {
return err
}
if withdefault {
datax.LoadDefault(config)
}
}
return init(config)
}
func getConfigWithMode(conf string) (string, error) {
if _, err := os.Stat(conf); os.IsNotExist(err) {
// check mode
confname := path.Base(conf)
mode := os.Getenv("SERVER_MODE")
conf = path.Join(path.Dir(conf), mode+"."+confname)
if _, err := os.Stat(conf); err != nil {
return "", err
}
return conf, nil
} else if err != nil {
return "", err
}
return conf, nil
}