-
Notifications
You must be signed in to change notification settings - Fork 1
/
vhelp.go
97 lines (60 loc) · 1.63 KB
/
vhelp.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
97
package vhelp
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
var cb func(e fsnotify.Event)
var watch bool
var configs map[string]*viper.Viper
var paths []string
func init (){
watch = false
configs = make(map[string]*viper.Viper)
exefull, _ := os.Executable()
exe := filepath.Base(exefull)
AddPath("/etc/" + exe) // path to look for the config file in
AddPath("$HOME/." + exe) // call multiple times to add many search paths
AddPath(".") // optionally look for config in the working directory
}
func AddPath(pth string){
paths = append(paths,pth)
}
func ResetPath() {
paths = []string{}
}
func OnChange(fn func(e fsnotify.Event)){
watch = true
cb = fn
}
func Load(file string){
if(len(file)==0){
file = "config"
}
runtime_viper := viper.New()
runtime_viper.SetConfigName(file) // name of config file (without extension)
runtime_viper.SetConfigType("json") // REQUIRED if the config file does not have the extension in the name
for _,p := range paths{
runtime_viper.AddConfigPath(p)
}
err := runtime_viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
if(watch==true) {
runtime_viper.WatchConfig()
runtime_viper.OnConfigChange(cb)
}
configs[file] = runtime_viper
}
func Get(name string) (*viper.Viper,error){
var ok bool
var runtime_viper *viper.Viper
if runtime_viper, ok = configs[name]; !ok {
return nil,errors.New("Not Found")
}
return runtime_viper,nil
}