liuxiaolong
2020-08-10 9358e5ec2d2b65fec4ef9a1be7d1a1e1e2cf9d2d
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package util
 
import (
    "crypto/hmac"
    "crypto/md5"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "fmt"
    "math/rand"
    "os"
    "os/exec"
    "path/filepath"
    "strconv"
    "strings"
    "time"
    "unsafe"
)
 
func Sha256(message string) string {
    h := sha256.New()
    h.Write([]byte(message))
    res := h.Sum(nil)
    return hex.EncodeToString(res)
}
 
func ComputeHmacSha256Base64(message string, secret string) string {
    key := []byte(secret)
    h := hmac.New(sha256.New, key)
    h.Write([]byte(message))
    abs := h.Sum(nil)
    return base64.StdEncoding.EncodeToString(abs)
}
 
 
func Hik_ComputeSignatureBase64(appKey string, appSecret string, httpMethod string, accept string, contentType string, date string, url string) string {
    httpHeaders := httpMethod +"\n" + accept + "\n" + contentType + "\n"+ date +"\n"
    customHeaders := "x-ca-key:"+ appKey +"\n"
    msg := httpHeaders + customHeaders + url
    return ComputeHmacSha256Base64(msg, appSecret)
}
 
type SliceMock struct {
    addr uintptr
    len int
    cap int
}
 
func GetIBytes(v interface{}) []byte {
    len := unsafe.Sizeof(v)
    dataBytes := &SliceMock{
        addr: uintptr(unsafe.Pointer(&v)),
        cap: int(len),
        len: int(len),
    }
    b := *(*[]byte)(unsafe.Pointer(dataBytes))
    return b
}
 
func MD5Base64(s []byte) string {
    sum := md5.Sum(s)
    return base64.StdEncoding.EncodeToString(sum[:])
}
 
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
}
 
//生成区间随机数
func RandInt(min, max int) int {
    if min >= max || min ==0 ||max == 0 {
        return max
    }
    return rand.Intn(max-min) + min
}
 
 
func GetAppRootPath() string {
    file,err:= exec.LookPath(os.Args[0])
    if err != nil {
        return ""
    }
    p, err := filepath.Abs(file)
    if err != nil {
        return ""
    }
    return filepath.Dir(p)
}