forked from heetch/regula
-
Notifications
You must be signed in to change notification settings - Fork 0
/
param.go
102 lines (83 loc) · 1.94 KB
/
param.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
96
97
98
99
100
101
102
package regula
import (
"strconv"
"github.com/heetch/regula/rule"
"github.com/pkg/errors"
)
// Params is a map based rule.Params implementation.
type Params map[string]interface{}
// GetString extracts a string parameter corresponding to the given key.
func (p Params) GetString(key string) (string, error) {
v, ok := p[key]
if !ok {
return "", rule.ErrParamNotFound
}
s, ok := v.(string)
if !ok {
return "", rule.ErrParamTypeMismatch
}
return s, nil
}
// GetBool extracts a bool parameter corresponding to the given key.
func (p Params) GetBool(key string) (bool, error) {
v, ok := p[key]
if !ok {
return false, rule.ErrParamNotFound
}
b, ok := v.(bool)
if !ok {
return false, rule.ErrParamTypeMismatch
}
return b, nil
}
// GetInt64 extracts an int64 parameter corresponding to the given key.
func (p Params) GetInt64(key string) (int64, error) {
v, ok := p[key]
if !ok {
return 0, rule.ErrParamNotFound
}
i, ok := v.(int64)
if !ok {
return 0, rule.ErrParamTypeMismatch
}
return i, nil
}
// GetFloat64 extracts a float64 parameter corresponding to the given key.
func (p Params) GetFloat64(key string) (float64, error) {
v, ok := p[key]
if !ok {
return 0, rule.ErrParamNotFound
}
f, ok := v.(float64)
if !ok {
return 0, rule.ErrParamTypeMismatch
}
return f, nil
}
// Keys returns the list of all the keys.
func (p Params) Keys() []string {
keys := make([]string, 0, len(p))
for k := range p {
keys = append(keys, k)
}
return keys
}
// EncodeValue returns the string representation of the selected value.
func (p Params) EncodeValue(key string) (string, error) {
v, ok := p[key]
if !ok {
return "", rule.ErrParamNotFound
}
switch t := v.(type) {
case string:
return t, nil
case int64:
return strconv.FormatInt(t, 10), nil
case float64:
return strconv.FormatFloat(t, 'f', 6, 64), nil
case bool:
return strconv.FormatBool(t), nil
default:
return "", errors.Errorf("type %t is not supported", t)
}
}