forked from gogap/spirit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
95 lines (84 loc) · 2.42 KB
/
options.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
91
92
93
94
95
package spirit
import (
"reflect"
"strconv"
"github.com/gogap/env_json"
"github.com/gogap/errors"
)
type Options map[string]interface{}
func (p Options) Serialize() (str string, err error) {
var data []byte
if data, err = env_json.MarshalIndent(&p, "", " "); err != nil {
return
}
str = string(data)
return
}
func (p Options) GetStringValue(key string) (value string, err error) {
if val, exist := p[key]; !exist {
err = ERR_OPTIONS_KEY_NOT_EXIST.New(errors.Params{"key": key})
return
} else if strVal, ok := val.(string); !ok {
err = ERR_OPTIONS_VALUE_TYPE_ERROR.New(errors.Params{"key": key, "value": val, "type": "string", "realType": getValueType(val)})
return
} else {
value = strVal
}
return
}
func (p Options) GetBoolValue(key string) (value bool, err error) {
if val, exist := p[key]; !exist {
err = ERR_OPTIONS_KEY_NOT_EXIST.New(errors.Params{"key": key})
return
} else if boolVal, ok := val.(bool); !ok {
err = ERR_OPTIONS_VALUE_TYPE_ERROR.New(errors.Params{"key": key, "value": val, "type": "bool", "realType": getValueType(val)})
return
} else {
value = boolVal
}
return
}
func (p Options) GetInt64Value(key string) (value int64, err error) {
if val, exist := p[key]; !exist {
err = ERR_OPTIONS_KEY_NOT_EXIST.New(errors.Params{"key": key})
return
} else if intVal, ok := val.(int64); !ok {
switch typedVal := val.(type) {
case float64:
value = int64(typedVal)
case int:
value = int64(typedVal)
case int32:
value = int64(typedVal)
case string:
if intV, e := strconv.Atoi(typedVal); e != nil {
err = ERR_OPTIONS_VAL_TYPE_CONV_FAILED.New(errors.Params{"key": key, "value": val, "type": "int64", "realType": getValueType(val), "err": e})
return
} else {
value = int64(intV)
}
default:
err = ERR_OPTIONS_VALUE_TYPE_ERROR.New(errors.Params{"key": key, "value": val, "type": "int64", "realType": getValueType(val)})
return
}
return
} else {
value = intVal
}
return
}
func (p Options) GetFloat64Value(key string) (value float64, err error) {
if val, exist := p[key]; !exist {
err = ERR_OPTIONS_KEY_NOT_EXIST.New(errors.Params{"key": key})
return
} else if floatVal, ok := val.(float64); !ok {
err = ERR_OPTIONS_VALUE_TYPE_ERROR.New(errors.Params{"key": key, "value": val, "type": "float64", "realType": getValueType(val)})
return
} else {
value = floatVal
}
return
}
func getValueType(v interface{}) string {
return reflect.TypeOf(v).Name()
}