forked from wendal/gor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
70 lines (62 loc) · 1.34 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
59
60
61
62
63
64
65
66
67
68
69
70
package gor
import (
"bytes"
"encoding/json"
"github.com/wendal/goyaml2"
"io"
"io/ioutil"
"log"
"os"
)
// 读取配置文件()
func ReadConfig(root string) (cnf map[string]interface{}, err error) {
cnf, err = ReadYmlCnf(root)
return
}
// 读取YAML格式的配置文件(兼容JSON)
func ReadYmlCnf(root string) (map[string]interface{}, error) {
return ReadYml(root + "/" + CONFIG_YAML)
}
// 从文件读取YAML
func ReadYml(path string) (cnf map[string]interface{}, err error) {
err = nil
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
cnf, err = ReadYmlReader(f)
return
}
// 从Reader读取YAML
func ReadYmlReader(r io.Reader) (cnf map[string]interface{}, err error) {
err = nil
buf, err := ioutil.ReadAll(r)
if err != nil || len(buf) < 3 {
return
}
if string(buf[0:1]) == "{" {
log.Println("Look lile a Json, try it")
err = json.Unmarshal(buf, &cnf)
if err == nil {
log.Println("It is Json Map")
return
}
}
_map, _err := goyaml2.Read(bytes.NewBuffer(buf))
if _err != nil {
log.Println("Goyaml2 ERR>", string(buf), _err)
//err = goyaml.Unmarshal(buf, &cnf)
err = _err
return
}
if _map == nil {
log.Println("Goyaml2 output nil? Pls report bug\n" + string(buf))
}
cnf, ok := _map.(map[string]interface{})
if !ok {
log.Println("Not a Map? >> ", string(buf), _map)
cnf = nil
}
return
}