This repository has been archived by the owner on Oct 26, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
78 lines (67 loc) · 1.82 KB
/
util.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
package gormx
import (
"fmt"
"reflect"
)
func getValueAndType(structData interface{}) (reflect.Value, reflect.Type, error) {
rv := reflect.ValueOf(structData)
if !rv.IsValid() {
return reflect.Value{}, nil, fmt.Errorf("gormx's data is invalid")
}
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return reflect.Value{}, nil, fmt.Errorf("data's kind must be struct, but got '%s'", rv.Kind())
}
rt := rv.Type()
return rv, rt, nil
}
func packPanicError(r interface{}) (err error) {
switch je := r.(type) {
case error:
return je
default:
return fmt.Errorf("gormx panic: %s", r)
}
}
func interfaceToSlice(v any) []any {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array {
panic("interfaceToSlice: v must be slice")
}
sliceType := rv.Type().Elem()
slice := make([]any, rv.Len())
for i := 0; i < rv.Len(); i++ {
x := reflect.New(sliceType).Elem()
x.Set(rv.Index(i))
slice[i] = x.Interface()
}
return slice
}
func isEmptyValue(rv reflect.Value) bool {
// data may be string, int, *string, slice, check data is empty
// example: "", 0, nil, []string{}, []int{}, []*string{}, []*int{}
switch rv.Kind() {
case reflect.String:
return rv.String() == ""
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return rv.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return rv.Uint() == 0
case reflect.Float32, reflect.Float64:
return rv.Float() == 0
case reflect.Bool:
return !rv.Bool()
case reflect.Interface, reflect.Ptr:
return rv.IsNil()
case reflect.Invalid:
return true
case reflect.Complex64, reflect.Complex128:
return rv.Complex() == 0
case reflect.Slice, reflect.Array, reflect.Map:
return rv.IsNil() || rv.Len() == 0
default:
return false
}
}