-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
81 lines (66 loc) · 2.51 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
72
73
74
75
76
77
78
79
80
81
package cli
import (
"os"
"github.com/fredbi/go-cli/config"
"github.com/spf13/viper"
)
var (
// package-level options to load configurations
configOptions = []config.Option{}
// ConfigEnv defines the environment variable used by the Config() function
// to find the current environment (i.e. a deployment context such as "dev", "prod", etc.).
ConfigEnv = "CONFIG_ENV"
// ConfigDebugEnv defines the environment variable used to instruct the config loader
// to dump all config keys for debugging.
ConfigDebugEnv = "DEBUG_CONFIG"
)
// SetConfigOption defines package-level defaults for config options, when using
// ConfigForEnv or Config.
//
// By default, this package doesn't set any particular option and uses all defaults from the config package.
func SetConfigOptions(opts ...config.Option) {
configOptions = opts
}
// ConfigForEnv loads and merge a set of config files for a given environment and applies some default values.
//
// It assumes that config files follow the conventions defined by "github.com/fredbi/go-cli/config".
//
// It dies upon failure.
//
// Defaulters a applied after loading the config.
//
// Environment variable settings:
// - If the environment variable "DEBUG_CONFIG" is set, the loaded settings are dumped to standard output as JSON.
// - The environment variable "CONFIG_DIR" defines the folder where the root configuration is located.
func ConfigForEnv(env string, defaulters ...func(*viper.Viper)) *viper.Viper {
return ConfigForEnvWithOptions(env, configOptions, defaulters...)
}
// ConfigForEnvWithOptions loads and merge a set of config files for a given environment and applies
// some default values.
//
// This function accepts some config.Options to control where and how the configuration files should be loaded.
func ConfigForEnvWithOptions(env string, opts []config.Option, defaulters ...func(*viper.Viper)) *viper.Viper {
cfg, err := config.LoaderWithSecrets(opts...).LoadForEnv(env)
if err != nil {
die("loading config: %v", err)
return nil
}
for _, defaulter := range defaulters {
defaulter(cfg)
}
if wantsDebug() {
cfg.Debug()
}
return cfg
}
// Config calls ConfigForEnv, with the current environment resolved from the variable "CONFIG_ENV".
//
// NOTE: users of this package may override the `ConfigEnv` variable to use a different
// environment variable.
func Config(defaulters ...func(*viper.Viper)) *viper.Viper {
env := config.GetenvOrDefault(ConfigEnv, "")
return ConfigForEnv(env, defaulters...)
}
func wantsDebug() bool {
return os.Getenv(ConfigDebugEnv) != ""
}