-
Notifications
You must be signed in to change notification settings - Fork 34
/
utils.go
68 lines (57 loc) · 1.21 KB
/
utils.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
package validation
import (
"fmt"
"reflect"
"regexp"
"strconv"
)
// toString converts an interface to a string.
func toString(v interface{}) string {
switch v := v.(type) {
case string:
return v
case int:
return strconv.Itoa(v)
default:
return fmt.Sprint(v)
}
}
// regex tests whether a pattern matches a string.
// It panics if the provided pattern is incorrect.
func regex(regex string, value string) bool {
matched, err := regexp.MatchString(regex, value)
if err != nil {
panic(err)
}
return matched
}
// getDeepValue returns the actual (final) reflect value.
func getDeepValue(v reflect.Value) reflect.Value {
switch v.Kind() {
case reflect.Interface:
return getDeepValue(v.Elem())
case reflect.Ptr:
return getDeepValue(reflect.Indirect(v))
default:
return v
}
}
// Returns true if the given value is empty.
func isEmpty(value interface{}) bool {
if value == nil {
return true
}
rv := reflect.ValueOf(value)
switch rv.Kind() {
case reflect.Map, reflect.Slice:
return rv.Len() == 0
case reflect.Ptr:
if rv.IsNil() {
return true
}
return isEmpty(rv.Elem().Interface())
default:
zero := reflect.Zero(rv.Type()).Interface()
return reflect.DeepEqual(value, zero)
}
}