2023-07-21 17:07:04 +08:00
|
|
|
|
package stringx
|
2022-07-27 15:36:56 +08:00
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"math/rand"
|
2024-10-16 17:24:50 +08:00
|
|
|
|
"strings"
|
2022-07-27 15:36:56 +08:00
|
|
|
|
"time"
|
2024-10-16 17:24:50 +08:00
|
|
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2022-07-27 15:36:56 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2023-11-07 21:05:21 +08:00
|
|
|
|
const Nums = "0123456789"
|
|
|
|
|
|
const LowerChars = "abcdefghigklmnopqrstuvwxyz"
|
|
|
|
|
|
const UpperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
2022-07-27 15:36:56 +08:00
|
|
|
|
|
|
|
|
|
|
// 生成随机字符串
|
2023-07-21 17:07:04 +08:00
|
|
|
|
func Rand(l int) string {
|
2023-11-07 21:05:21 +08:00
|
|
|
|
return RandByChars(l, Nums+LowerChars+UpperChars)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-10-16 17:24:50 +08:00
|
|
|
|
// RandUUID
|
|
|
|
|
|
func RandUUID() string {
|
|
|
|
|
|
return strings.Replace(uuid.New().String(), "-", "", -1)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-11-07 21:05:21 +08:00
|
|
|
|
// 根据传入的chars,随机生成指定位数的字符串
|
|
|
|
|
|
func RandByChars(l int, chars string) string {
|
|
|
|
|
|
strList := []byte(chars)
|
2022-07-27 15:36:56 +08:00
|
|
|
|
|
|
|
|
|
|
result := []byte{}
|
|
|
|
|
|
i := 0
|
|
|
|
|
|
|
|
|
|
|
|
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
|
|
|
|
charLen := len(strList)
|
|
|
|
|
|
for i < l {
|
|
|
|
|
|
new := strList[r.Intn(charLen)]
|
|
|
|
|
|
result = append(result, new)
|
|
|
|
|
|
i = i + 1
|
|
|
|
|
|
}
|
|
|
|
|
|
return string(result)
|
|
|
|
|
|
}
|