-
Notifications
You must be signed in to change notification settings - Fork 51
/
config.go
88 lines (71 loc) · 1.71 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
82
83
84
85
86
87
88
package config
import (
"bytes"
"github.com/apex/log"
"github.com/crawlab-team/go-trace"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"strings"
)
func init() {
// config instance
c := Config{Name: ""}
// init config file
if err := c.Init(); err != nil {
log.Warn("unable to init config")
return
}
// watch config change and load responsively
c.WatchConfig()
// init log level
c.initLogLevel()
}
type Config struct {
Name string
}
type InitConfigOptions struct {
Name string
}
func (c *Config) WatchConfig() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Infof("Config file changed: %s", e.Name)
})
}
func (c *Config) Init() (err error) {
// config
if c.Name != "" {
viper.SetConfigFile(c.Name) // if config file is set, load it accordingly
} else {
viper.AddConfigPath("./conf") // if no config file is set, load by default
viper.SetConfigName("config")
}
// config type as yaml
viper.SetConfigType("yaml") // default yaml
// auto env
viper.AutomaticEnv() // load matched environment variables
// env prefix
viper.SetEnvPrefix("CRAWLAB") // environment variable prefix as CRAWLAB
// replacer
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
// read default config
defaultConfBuf := bytes.NewBufferString(DefaultConfigYaml)
if err := viper.ReadConfig(defaultConfBuf); err != nil {
return trace.TraceError(err)
}
// merge config
if err := viper.MergeInConfig(); err != nil { // viper parsing config file
return err
}
return nil
}
func (c *Config) initLogLevel() {
// set log level
logLevel := viper.GetString("log.level")
l, err := log.ParseLevel(logLevel)
if err != nil {
l = log.InfoLevel
}
log.SetLevel(l)
}