-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.go
74 lines (65 loc) · 1.29 KB
/
strings.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
package util
import (
"bytes"
"crypto/rand"
"encoding/binary"
"fmt"
"github.com/google/uuid"
mathRand "math/rand"
"strings"
"time"
)
// 字符串工具包
//
const letters = "qwertyuipasdfghjkzxcvbnmQWERTYUIPASDFGHJKLZXCVBNM123456789!@#$%&[]"
var src = mathRand.NewSource(time.Now().UnixNano())
var size = len(letters)
// RandStr 随机字符串,返回n个字符
func RandStr(n int) (s string) {
var count = 0
buf := bytes.Buffer{}
for {
bs := Int64ToBytes(src.Int63())
for _, b := range bs {
i := b & 0xff
index := int(i) % size
buf.WriteByte(letters[index])
count++
if count >= n {
break
}
}
if count >= n {
break
}
}
s = buf.String()
return
}
// Int64ToBytes int64-->8byte
func Int64ToBytes(n int64) (bs []byte) {
bs = make([]byte, 8)
binary.BigEndian.PutUint64(bs, uint64(n))
return
}
// RandHexStr 随机字符串,hex表示.
//
// n:字节数,返回2n个hex字符
func RandHexStr(n int) (s string) {
randBytes := make([]byte, n)
_, _ = rand.Read(randBytes)
s = fmt.Sprintf("%x", randBytes)
return
}
func UUIDString() (s string) {
u, err := uuid.NewRandom()
if err != nil {
return
}
s = u.String()
s = strings.ToLower(strings.ReplaceAll(s, "-", ""))
return
}
func Join(delimiter string, s ...string) string {
return strings.Join(s, delimiter)
}