This repository has been archived by the owner on Jan 10, 2021. It is now read-only.
/
configor.go
96 lines (78 loc) · 2.09 KB
/
configor.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package configor
import (
"fmt"
"os"
"reflect"
"regexp"
)
type Configor struct {
*Config
}
type Config struct {
Environment string
ENVPrefix string
Debug bool
Verbose bool
Silent bool
UsePkger bool
// In case of json files, this field will be used only when compiled with
// go 1.10 or later.
// This field will be ignored when compiled with go versions lower than 1.10.
ErrorOnUnmatchedKeys bool
}
// New initialize a Configor
func New(config *Config) *Configor {
if config == nil {
config = &Config{}
}
if os.Getenv("CONFIGOR_DEBUG_MODE") != "" {
config.Debug = true
}
if os.Getenv("CONFIGOR_VERBOSE_MODE") != "" {
config.Verbose = true
}
if os.Getenv("CONFIGOR_SILENT_MODE") != "" {
config.Silent = true
}
if os.Getenv("CONFIGOR_USE_PKGER") != "" {
config.UsePkger = true
}
return &Configor{Config: config}
}
var testRegexp = regexp.MustCompile("_test|(\\.test$)")
// GetEnvironment get environment
func (configor *Configor) GetEnvironment() string {
if configor.Environment == "" {
if env := os.Getenv("CONFIGOR_ENV"); env != "" {
return env
}
if testRegexp.MatchString(os.Args[0]) {
return "test"
}
return "development"
}
return configor.Environment
}
// GetErrorOnUnmatchedKeys returns a boolean indicating if an error should be
// thrown if there are keys in the config file that do not correspond to the
// config struct
func (configor *Configor) GetErrorOnUnmatchedKeys() bool {
return configor.ErrorOnUnmatchedKeys
}
// Load will unmarshal configurations to struct from files that you provide
func (configor *Configor) Load(config interface{}, files ...string) (err error) {
defaultValue := reflect.Indirect(reflect.ValueOf(config))
if !defaultValue.CanAddr() {
return fmt.Errorf("Config %v should be addressable", config)
}
err = configor.load(config, files...)
return
}
// ENV return environment
func ENV() string {
return New(nil).GetEnvironment()
}
// Load will unmarshal configurations to struct from files that you provide
func Load(config interface{}, files ...string) error {
return New(nil).Load(config, files...)
}