-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
58 lines (50 loc) · 1.07 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
package config
import (
"fmt"
"github.com/fsnotify/fsnotify"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
"log"
)
var (
Hosts []string
UpdateInterval int
ImmediatelyAtStartup bool
)
// Init 使用viper读取配置文件
func Init() {
setConfigFile()
readConfig()
watchConfig()
}
func readConfig() {
err := viper.ReadInConfig()
if err != nil {
log.Fatalln(fmt.Errorf("Fatal error config file: %s \n", err))
}
load()
}
func load() {
Hosts = viper.GetStringSlice("hosts")
UpdateInterval = viper.GetInt("update_interval")
ImmediatelyAtStartup = viper.GetBool("immediately_at_startup")
}
func watchConfig() {
viper.WatchConfig()
viper.OnConfigChange(func(in fsnotify.Event) {
fmt.Println("config file changed:", in.Name)
load()
})
}
func setConfigFile() {
var file string
flag.StringVarP(&file, "config", "c", "", "please specified config file.")
flag.Parse()
if file == "" {
file = "auto-github-hosts.toml"
viper.AddConfigPath(".")
viper.AddConfigPath("./config")
}
viper.SetConfigFile(file)
viper.SetConfigType("toml")
}