-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
47 lines (42 loc) · 1.41 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
package viper
import (
"fmt"
"github.com/117s/x/consts"
"github.com/spf13/viper"
"os"
)
// MustLoadConfig load configurations from yml viper file
// All services should provide a configuration file along with its docker images.
// And all configurations inside the viper file can be over write by corresponding environment variable
// It’s important to recognize that Viper treats ENV variables as case-sensitive.
func MustLoadConfig(envPrefix string, configPath *string, configurations interface{}) *viper.Viper {
var config string
if configPath == nil {
if configEnv := os.Getenv(consts.ConfigPath); configEnv == "" {
config = consts.DefaultConfigPath
fmt.Printf("can not find viper path or viper path environment variable, using default viper path: %s\n", config)
} else {
config = configEnv
fmt.Printf("get viper path from env:%s, value:%s\n", consts.ConfigPath, config)
}
} else {
config = *configPath
fmt.Printf("you are using viper file from: %v\n", config)
}
v := viper.New()
v.SetConfigFile(config)
v.SetConfigType("yaml")
v.SetEnvPrefix(envPrefix)
v.AutomaticEnv()
// Read Config from disk and env vars
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error viper file: %s \n", err))
}
fmt.Println("Config loaded successfully...")
err = v.Unmarshal(&configurations)
if err != nil {
panic(fmt.Errorf("Fatal unmarshal configurations: %s \n", err))
}
return v
}