forked from childe/gohangout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yaml_config_parser.go
54 lines (47 loc) · 985 Bytes
/
yaml_config_parser.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
yaml "gopkg.in/yaml.v2"
)
type YamlParser struct{}
func (yp *YamlParser) parse(filepath string) (map[string]interface{}, error) {
var (
buffer []byte
err error
)
if strings.HasPrefix(filepath, "http://") || strings.HasPrefix(filepath, "https://") {
resp, err := http.Get(filepath)
if err != nil {
return nil, err
}
defer resp.Body.Close()
buffer, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
} else {
configFile, err := os.Open(filepath)
if err != nil {
return nil, err
}
fi, _ := configFile.Stat()
if fi.Size() == 0 {
return nil, fmt.Errorf("config file (%s) is empty", filepath)
}
buffer = make([]byte, fi.Size())
_, err = configFile.Read(buffer)
if err != nil {
return nil, err
}
}
config := make(map[string]interface{})
err = yaml.Unmarshal(buffer, &config)
if err != nil {
return nil, err
}
return config, nil
}