-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_setup.go
62 lines (52 loc) · 1.3 KB
/
config_setup.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
package config
import (
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"os"
"rule_service/commons"
"sync"
)
func NewViperConfig() *Configuration {
viper.SetConfigName(GetConfigName())
viper.AddConfigPath(commons.CONFIG_DIR)
if err := viper.ReadInConfig(); err != nil {
logrus.Fatalf("Error reading config file, %s", err)
}
var configuration Configuration
err := viper.Unmarshal(&configuration)
if err != nil {
logrus.Fatalf("unable to decode into struct, %v", err)
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
err := viper.Unmarshal(&configuration)
if err != nil {
logrus.Fatalf("unable to decode into struct, %v", err)
}
logrus.Info("Config file changed:", e.Name)
})
return &configuration
}
func GetConfigName() string {
env := os.Getenv(commons.EnvVariable)
if env == commons.DEV {
return commons.DEV_CONFIG_PATH
} else if env == commons.QA {
return commons.QA_CONFIG_PATH
} else if env == commons.PROD {
return commons.PROD_CONFIG_PATH
} else {
logrus.Fatalf("ENVIRONMENT variable is not set")
}
return commons.EMPTY
}
var once sync.Once
var conf *Configuration
func GetInstance() *Configuration {
once.Do(func() {
conf = NewViperConfig()
defer logrus.Info("config setup completed")
})
return conf
}