-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
55 lines (48 loc) · 1.01 KB
/
helper.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
package rabbit
import (
"math/rand"
"reflect"
"time"
)
func init() {
rand.New(rand.NewSource(time.Now().UnixNano()))
}
var letterRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyz")
var numberRunes = []rune("0123456789")
func randRunes(n int, source []rune) string {
b := make([]rune, n)
for i := range b {
b[i] = source[rand.Intn(len(source))]
}
return string(b)
}
func RandText(n int) string {
return randRunes(n, letterRunes)
}
func RandNumberText(n int) string {
return randRunes(n, numberRunes)
}
func StructAsMap(form any, fields []string) (vals map[string]any) {
vals = make(map[string]any)
v := reflect.ValueOf(form)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return vals
}
for i := 0; i < len(fields); i++ {
k := v.FieldByName(fields[i])
if !k.IsValid() || k.IsZero() {
continue
}
if k.Kind() == reflect.Ptr {
if !k.IsNil() {
vals[fields[i]] = k.Elem().Interface()
}
} else {
vals[fields[i]] = k.Interface()
}
}
return vals
}