liuxiaolong
2020-05-27 0b026a39029cf04954e2fc2ffe52e40720a7faa7
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
package util
 
import (
    "encoding/json"
    "fmt"
    "github.com/gin-gonic/gin"
    "math/rand"
    "strconv"
    "strings"
    "time"
    "video-analysis-shop/api/code"
)
 
func ResponseFormat(c *gin.Context, respStatus *code.Code, data interface{}) {
    if respStatus == nil {
        respStatus = code.RequestParamError
    }
    c.JSON(respStatus.Status, gin.H{
        "code":    respStatus.Status,
        "success": respStatus.Success,
        "msg":     respStatus.Message,
        "data":    data,
    })
    return
}
 
func GenValidateCode(width int) string {
    numeric := [10]byte{0,1,2,3,4,5,6,7,8,9}
    r := len(numeric)
    rand.Seed(time.Now().UnixNano())
 
    var sb strings.Builder
    for i := 0; i < width; i++ {
        fmt.Fprintf(&sb, "%d", numeric[ rand.Intn(r) ])
    }
    str := sb.String()
    if strings.HasPrefix(str, "0") {
        pI := RandInt(1,9)
        str = strconv.Itoa(pI) + str[1:]
    }
    return str
}
 
const (
    KC_RAND_KIND_NUM   = 0  // 纯数字
    KC_RAND_KIND_LOWER = 1  // 小写字母
    KC_RAND_KIND_UPPER = 2  // 大写字母
    KC_RAND_KIND_ALL   = 3  // 数字、大小写字母
)
 
// 随机字符串
func Krand(size int, kind int) []byte {
    ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
    is_all := kind > 2 || kind < 0
    rand.Seed(time.Now().UnixNano())
    for i :=0; i < size; i++ {
        if is_all { // random ikind
            ikind = rand.Intn(3)
        }
        scope, base := kinds[ikind][0], kinds[ikind][1]
        result[i] = uint8(base+rand.Intn(scope))
    }
    return result
}
 
//生成区间随机数
func RandInt(min, max int) int {
    if min >= max || min ==0 ||max == 0 {
        return max
    }
    return rand.Intn(max-min) + min
}
 
func Struct2Map(obj interface{}) map[string]interface{} {
    resultMap := make(map[string]interface{}, 0)
    bytesData, err := json.Marshal(obj)
    if err != nil {
        return resultMap
    }
    json.Unmarshal(bytesData, &resultMap)
    return resultMap
}