-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.go
55 lines (43 loc) · 1.5 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
package snakelet
import (
"fmt"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
)
func InitAndLoad(configStruct interface{}, cfgFile string) (*viper.Viper, error) {
return InitAndLoadWithParams(configStruct, cfgFile, validator.New())
}
// InitAndLoad
// if `cfgFile` == "", it will use only the default values otherwise, it will load the specified config file
// will return an error if occurred, and an instance of viper configuration
func InitAndLoadWithParams(configStruct interface{}, cfgFile string, validate *validator.Validate) (*viper.Viper, error) {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
}
// read from config file
if err := viper.ReadInConfig(); err != nil {
if _, isConfigFileNotFoundError := err.(viper.ConfigFileNotFoundError); !isConfigFileNotFoundError {
return viper.GetViper(), err
}
}
// set default
var decodedConfig map[string]interface{}
err := mapstructure.Decode(configStruct, &decodedConfig)
if err != nil {
return viper.GetViper(), err
}
for k, v := range decodedConfig {
viper.SetDefault(k, v)
}
// unmarshal config file / env variables to exact struct, overriding potential defaults
// fail if the config does not match the struct
err = viper.UnmarshalExact(&configStruct)
if err != nil {
return viper.GetViper(), err
}
if err := validate.Struct(configStruct); err != nil {
return viper.GetViper(), fmt.Errorf("Missing required config attributes %w\n", err)
}
return viper.GetViper(), err
}