常用函数

Yishto 2021-08-20 21:46:28
Categories: Tags:
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
// map|slice|array 中是否包含某个值
func Contains(array interface{}, val interface{}) (index int) {
index = -1
switch reflect.TypeOf(array).Kind() {
case reflect.Slice: {
s := reflect.ValueOf(array)
for i := 0; i < s.Len(); i++ {
if reflect.DeepEqual(val, s.Index(i).Interface()) {
index = i
return
}
}
}
}
return
}

// 打乱map顺序
func Shuffle(slice []map[string]string) {
r := rand.New(rand.NewSource(time.Now().Unix()))
for len(slice) > 0 {
n := len(slice)
randIndex := r.Intn(n)
slice[n-1], slice[randIndex] = slice[randIndex], slice[n-1]
slice = slice[:n-1]
}
}

//判断是不是一个数字
func IsNumber(v interface{}) bool{
result,_ := regexp.MatchString( "\\d+" ,fmt.Sprint(v))
return result
}

//md5加密
func GetMd5String(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}

//进行zlib压缩
func DoZlibCompress(src []byte) []byte {
var in bytes.Buffer
w := zlib.NewWriter(&in)
w.Write(src)
w.Close()
return in.Bytes()
}

//进行zlib解压缩
func DoZlibUnCompress(compressSrc []byte) []byte {
b := bytes.NewReader(compressSrc)
var out bytes.Buffer
r, _ := zlib.NewReader(b)
io.Copy(&out, r)
return out.Bytes()
}

//gzip 压缩
func GzipEncode(in []byte) ([]byte, error) {
var (
buffer bytes.Buffer
out []byte
err error
)
writer := gzip.NewWriter(&buffer)
_, err = writer.Write(in)
if err != nil {
writer.Close()
return out, err
}
err = writer.Close()
if err != nil {
return out, err
}

return buffer.Bytes(), nil
}

// gzip 解压
func GzipDecode(in []byte) ([]byte, error) {
reader, err := gzip.NewReader(bytes.NewReader(in))
if err != nil {
var out []byte
return out, err
}
defer reader.Close()

return ioutil.ReadAll(reader)
}

// base64 encode
base64.StdEncoding.EncodeToString([]byte(txt))

// base64 decode
base64.RawURLEncoding.DecodeString(decodeStr)