-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadconfig.go
86 lines (76 loc) · 1.82 KB
/
loadconfig.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
package main
import (
"fmt"
"github.com/davidhenrygao/GoGameServer/module/config"
"reflect"
)
//Required configurations when server start.
type initCfg struct {
Id int
Ip string
Port int
LogDir string
LogFileName string
LogLevel string
Logstderr bool
}
type loadField struct {
name string
defult interface{} //Can't be omitted if is nil.
}
//Must match the fields in the struct initCfg.
var cfgMap = map[string]loadField{
"Id": {"id", nil},
"Ip": {"ip", "127.0.0.1"},
"Port": {"port", nil},
"LogDir": {"log,dir", "./log/"},
"LogFileName": {"log,filename", "server"},
"LogLevel": {"log,level", "error"},
"Logstderr": {"log,stderr", false},
}
func loadKindCfg(name string, kind reflect.Kind) (interface{}, error) {
cfg := config.Cfg
var val interface{}
var err error
switch kind {
case reflect.Bool:
val, err = cfg.Bool(name)
case reflect.Int:
val, err = cfg.Int(name)
case reflect.String:
val, err = cfg.Value(name)
default:
panic(fmt.Sprintf("Unsupported configure type: %s.", kind.String()))
}
return val, err
}
//useing reflection to load configure.
func loadConfig(file string) initCfg {
err := config.LoadCfgFile(cfgFile)
if err != nil {
panic(fmt.Sprintf("Load configure file error: %+v\n", err))
}
var iCfg initCfg
t := reflect.TypeOf(iCfg)
v := reflect.ValueOf(&iCfg).Elem()
nf := t.NumField()
for i := 0; i < nf; i++ {
f := t.Field(i)
name := f.Name
loadf, ok := cfgMap[name]
if !ok {
panic(fmt.Sprintf("Miss load field(%s) in the cfgMap.", name))
}
kind := f.Type.Kind()
val, err := loadKindCfg(loadf.name, kind)
if err != nil {
if loadf.defult == nil {
panic(fmt.Sprintf("%+v\n", err))
} else {
val = loadf.defult
}
}
v.FieldByName(name).Set(reflect.ValueOf(val))
}
return iCfg
}