-
Notifications
You must be signed in to change notification settings - Fork 12
/
config.go
90 lines (77 loc) · 1.75 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package hera
import (
"errors"
"io/ioutil"
"github.com/xcodecraft/hera/yaml"
)
var SERVER = make(map[interface{}]string)
var run_mode string
var need_mode = make(map[string]bool)
type Config struct {
confPath string
data map[interface{}]interface{}
}
func NewConfig(filename string) *Config {
if filename == "" {
panic("config file is empty")
}
config := &Config{
confPath: filename,
data: make(map[interface{}]interface{}),
}
err := config.Init(filename)
if err != nil {
panic("config init fail")
}
return config
}
func (this *Config) Init(filename string) error {
stream, err := ioutil.ReadFile(filename)
if err != nil {
return errors.New("load config file has error")
}
return yaml.Unmarshal(stream, this.data)
}
func MakeServerVar(config *Config) error {
if config == nil {
return errors.New("config is empty")
}
dict := config.data
envDict, ok := dict["__env"];
if ok == false {
panic("conf.__env is illegal")
}
for _, env:= range envDict.([]interface{}){
need_mode[env.(string)] = true
}
mode, ok := dict["__mode"]
run_mode = mode.(string)
if ok == false || need_mode[run_mode] != true {
panic("conf.__mode is illegal")
}
CpMapValue(dict, &SERVER)
return nil
}
func CpMapValue(from interface{}, to *map[interface{}]string) {
switch fromVal := from.(type) {
case map[interface{}]interface{}:
for key, value := range fromVal {
if need_mode[key.(string)] == true && key != run_mode {
continue
}
_, ok_map := value.(map[interface{}]interface{})
_, ok_slice := value.([]interface{})
if !ok_map && !ok_slice {
(*to)[key] = value.(string)
} else {
CpMapValue(value, to)
}
}
case []interface{}:
for _, value := range fromVal {
CpMapValue(value, to)
}
default:
return
}
}