-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconf.go
74 lines (64 loc) · 1.35 KB
/
conf.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
package goconf
import (
"io"
"log"
"strings"
"time"
)
type config struct {
modTime time.Time
info map[string]interface{}
}
type Config struct {
name string
}
func (c *Config) Get(key string) interface{} {
return confMapping[c.name].info[key]
}
var confMapping map[string]Config
func LoadConfig(filename string) (*Config, error) {
if confMapping == nil {
confMapping = make(map[string]time.Time)
confMapping[filename] = time.Now().Add(-100) // Arbitrary time before now to force a reload
go hotReload()
}
return &Config{name:filename}
}
func loadConfig(name string) (map[string]interface{}, error) {
f, err = os.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
split = strings.Split(name, '.')
format := split[len(split) - 1]
switch format {
case "json":
var rval interface{}
decoder := json.NewDecoder(f)
err := decoder.Decode(rval)
if err != nil {
return nil, err
}
return rval, nil
default:
return nil, fmt.Error("Invalid format: %s", format)
}
}
func hotReload() {
for {
for name, conf := range confMapping {
fi, err := os.Stat(name)
if err != nil {
log.Printf("Error reading file %v\n", name)
}
if conf.modTime.Before(fi.ModTime()) {
conf, err := loadConfig(name)
if err != nil {
log.Printf("Error reading file %v\n", name)
}
confMapping[name] = conf
}
}
}
}