forked from sleey/common-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
67 lines (57 loc) · 1.76 KB
/
init.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
package config
import (
"bytes"
"fmt"
"github.com/fsnotify/fsnotify"
log "github.com/sleey/common-go/log"
"github.com/spf13/viper"
)
// NewConfigFromFile instantiate new configuration instance
// Config in this example is read-only, you can't set it on the fly
// so don't return any possible interface to do so
func NewConfigFromFile(configName, configType, filePath string, options NewConfigOptions) (err error) {
if vInstances[configName] != nil {
err = fmt.Errorf("Viper instance is already initialized for %s", configName)
return
}
vInstances[configName] = viper.New()
vInstances[configName].SetConfigType(configType)
vInstances[configName].SetConfigFile(filePath)
if options.Defaults != nil {
defaults := options.Defaults
for key, value := range defaults {
vInstances[configName].SetDefault(key, value)
}
}
if options.DefaultName != "" {
DefaultConfigName = options.DefaultName
}
err = vInstances[configName].ReadInConfig()
if err != nil {
return
}
if options.IsWatch {
vInstances[configName].WatchConfig()
vInstances[configName].OnConfigChange(func(e fsnotify.Event) {
log.WithField("configName", e.Name).Info("Config File Changed")
})
}
return
}
// NewConfigFromString instantiate new configuration instance using string, useful for testing
func NewConfigFromString(configName, value string, options NewConfigOptions) (err error) {
if vInstances[configName] != nil {
err = fmt.Errorf("Viper instance is already initialized for %s", configName)
return
}
vInstances[configName] = viper.New()
valueByte := []byte(value)
viper.ReadConfig(bytes.NewBuffer(valueByte))
if options.Defaults != nil {
defaults := options.Defaults
for key, value := range defaults {
vInstances[configName].SetDefault(key, value)
}
}
return
}