-
Notifications
You must be signed in to change notification settings - Fork 3
/
basic.go
59 lines (49 loc) · 1019 Bytes
/
basic.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
package validator
import (
"fmt"
"reflect"
"strings"
)
func indirectValue(v any) (value any, isValid bool) {
val := reflect.ValueOf(v)
if !val.IsValid() || (val.Kind() == reflect.Ptr && val.IsNil()) {
return nil, false
}
val = reflect.Indirect(val)
if !val.IsValid() {
return nil, false
}
return val.Interface(), true
}
func valueIsEmpty(value reflect.Value) bool {
if !value.IsValid() {
return true
}
switch value.Kind() {
case reflect.Slice, reflect.Map:
return value.IsNil() || value.Len() == 0
case reflect.Array, reflect.Struct:
return value.IsZero()
case reflect.String:
return len(strings.TrimSpace(value.String())) == 0
case reflect.Ptr:
return value.IsNil() || valueIsEmpty(value.Elem())
default:
return false
}
}
func toString(v any) (string, bool) {
if v == nil {
return "", false
}
switch v := v.(type) {
case string:
return v, true
case *string:
return *v, true
}
if i, ok := v.(fmt.Stringer); ok {
return i.String(), true
}
return "", false
}