/
config.go
71 lines (60 loc) · 1.34 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 config
import (
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
type option struct {
cfg string
name string
envPrefix string
configType string
}
type Option func(*option)
func WithConfigFile(cfg string) Option {
return func(o *option) {
o.cfg = cfg
}
}
func WithConfigType(configType string) Option {
return func(o *option) {
o.configType = configType
}
}
func WithName(name string) Option {
return func(o *option) {
o.name = name
}
}
func WithEnvPrefix(envPrefix string) Option {
return func(o *option) {
o.envPrefix = envPrefix
}
}
// LoadConfig init Config
func LoadConfig(opts ...Option) error {
o := &option{
envPrefix: "x-iam",
configType: "yaml",
}
for _, opt := range opts {
opt(o)
}
if o.cfg != "" {
// Use config file from the flag.
viper.SetConfigFile(o.cfg)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
return err
}
// Search config in home directory with name ".migrate" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(o.name)
viper.SetConfigType(o.configType)
}
viper.SetEnvPrefix(o.envPrefix) // set environment variables prefix to avoid conflict
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
return viper.ReadInConfig()
}