-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
54 lines (45 loc) · 974 Bytes
/
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
package app
import (
"github.com/astaxie/beego/logs"
"github.com/fsnotify/fsnotify"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"log"
"os"
"strings"
)
type Config struct {
Name string
}
func InitConfig() {
cfg := pflag.StringP("config", "c", "", "config file path.")
pflag.Parse()
c := Config{
Name: *cfg,
}
if err := c.initViper(); err != nil {
log.Printf("初始化 config 服务出错:%s\n", err.Error())
os.Exit(1)
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
logs.Debug("Config file changed:" + e.Name)
})
}
func (c *Config) initViper() error {
if c.Name != "" {
viper.SetConfigFile(c.Name)
} else {
viper.AddConfigPath("conf")
viper.SetConfigName("config")
}
viper.SetConfigType("yaml")
viper.AutomaticEnv()
viper.SetEnvPrefix("ALBEDO")
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
return err
}
return nil
}