This repository has been archived by the owner on May 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
105 lines (83 loc) · 1.83 KB
/
params.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
103
104
105
package system
import (
"fmt"
"regexp"
"strings"
)
const EMAIL_REGEX string = `^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$`
type Params map[string]interface{}
func (p Params) Add(key string, value interface{}) {
p[key] = value
}
func (p Params) Get(key string) string {
if val, ok := p[key]; ok {
return fmt.Sprintf("%v", val)
}
return ""
}
func (p Params) GetI(key string) interface{} {
if val, ok := p[key]; ok {
return val
}
return nil
}
func (p Params) GetP(key string) Params {
if val, ok := p[key]; ok {
return Params(val.(map[string]interface{}))
}
return Params{}
}
func (p Params) GetA(key string) []interface{} {
if val, ok := p[key]; ok {
return val.([]interface{})
}
return nil
}
func (p Params) GetAString(key string) []string {
result := make([]string, 0)
if val, ok := p[key]; ok {
if val, ok := val.([]interface{}); ok {
for _, v := range val {
if vs, ok := v.(string); ok {
result = append(result, vs)
}
}
}
return result
}
return nil
}
func (p Params) Required(keys ...string) error {
for _, key := range keys {
if ok := p.exists(p, key); !ok {
return fmt.Errorf("The parameter %s is required!", key)
}
}
return nil
}
func (p Params) ShouldBeEmail(key string) error {
if ok, _ := regexp.MatchString(EMAIL_REGEX, p.Get(key)); !ok {
return fmt.Errorf("Please provide valid email address!")
}
return nil
}
func (p Params) exists(input map[string]interface{}, key string) (ok bool) {
if input == nil {
return false
}
if index := strings.Index(key, "."); index != -1 {
pair := strings.SplitN(key, ".", 2)
params, asserted := input[pair[0]].(map[string]interface{})
if !asserted {
return false
}
ok = p.exists(params, pair[1])
} else {
var v interface{}
v, ok = input[key]
if s, isS := v.(string); isS && ok {
ok = (s != "")
}
}
return ok
}