-
Notifications
You must be signed in to change notification settings - Fork 2
/
conf.go
80 lines (67 loc) · 1.07 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
75
76
77
78
79
80
package conf
import (
"encoding/json"
"io/ioutil"
"path/filepath"
"strings"
)
//New new a Config
func New(file string) Config {
return Config{file: file}
}
type Config struct {
file string
maps map[string]interface{}
}
//Get name pattern key or key.key.key
//
func (c *Config) Get(name string) interface{} {
if c.maps == nil {
c.read()
}
if c.maps == nil {
return nil
}
// app.view.path
keys := strings.Split(name, ".")
l := len(keys)
if l == 1 {
return c.maps[name]
}
var ret interface{}
for i := 0; i < l; i++ {
if i == 0 {
ret = c.maps[keys[i]]
if ret == nil {
return nil
}
} else {
if m, ok := ret.(map[string]interface{}); ok {
ret = m[keys[i]]
} else {
if l == i-1 {
return ret
}
return nil
}
}
}
return ret
}
func (c *Config) read() {
if !filepath.IsAbs(c.file) {
file, err := filepath.Abs(c.file)
if err != nil {
panic(err)
}
c.file = file
}
bts, err := ioutil.ReadFile(c.file)
if err != nil {
panic(err)
}
err = json.Unmarshal(bts, &c.maps)
if err != nil {
panic(err)
}
}