-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
62 lines (51 loc) · 1.54 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
package cmd
import (
"strings"
"github.com/uthark/yttrium/internal/config"
"github.com/uthark/yttrium/internal/util"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file to use.")
rootCmd.PersistentFlags().Uint16("http-port", 8080, "HTTP Port to use")
util.Must(viper.BindPFlags(rootCmd.PersistentFlags()))
}
func initConfig() {
viper.SetEnvPrefix("YTTRIUM")
replacer := strings.NewReplacer("-", "_")
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv()
// read configuration.
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Search config in current directory with name ".yttrium" (without extension).
viper.AddConfigPath(".")
viper.SetConfigName(".yttrium")
}
if err := viper.ReadInConfig(); err != nil {
logger.Println("No config file found: ", err)
}
logger.Println("Config file used: ", viper.ConfigFileUsed())
logger.Println("Current configuration:", viper.AllSettings())
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
logger.Println("Config file changed:", e.Name, e.Op, e)
c := &config.Configuration{}
err := viper.Unmarshal(c)
if err != nil {
logger.Println("Unable to unmarshal config:", err)
}
config.SetDefaultConfiguration(c)
logger.Println(c)
restartServer()
})
c := &config.Configuration{}
util.Must(viper.Unmarshal(c))
config.SetDefaultConfiguration(c)
}