You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1011 B
44 lines
1011 B
|
20 hours ago
|
package publicmethod
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"math/rand"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
/*
|
||
|
|
*
|
||
|
|
@ 作者: 秦东
|
||
|
|
@ 时间: 2025-12-06 11:05:40
|
||
|
|
@ 功能: 随机字符串
|
||
|
|
*/
|
||
|
|
func GenerateRandomString(length int) (string, error) {
|
||
|
|
if length <= 0 {
|
||
|
|
return "", fmt.Errorf("长度必须大于0")
|
||
|
|
}
|
||
|
|
|
||
|
|
// 定义所有可能的字符:数字0-9,大写字母A-Z,小写字母a-z
|
||
|
|
allChars := "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz"
|
||
|
|
allCharsLen := len(allChars)
|
||
|
|
|
||
|
|
// 检查请求的长度是否超过可用字符数
|
||
|
|
if length > allCharsLen {
|
||
|
|
return "", fmt.Errorf("请求的长度(%d)超过了可用字符总数(%d)", length, allCharsLen)
|
||
|
|
}
|
||
|
|
|
||
|
|
// 将字符串转换为字节切片以便随机选择
|
||
|
|
chars := []byte(allChars)
|
||
|
|
|
||
|
|
// 使用当前时间作为随机种子
|
||
|
|
rand.Seed(time.Now().UnixNano())
|
||
|
|
|
||
|
|
// 随机打乱字符顺序
|
||
|
|
rand.Shuffle(allCharsLen, func(i, j int) {
|
||
|
|
chars[i], chars[j] = chars[j], chars[i]
|
||
|
|
})
|
||
|
|
|
||
|
|
// 取前length个字符作为结果
|
||
|
|
result := string(chars[:length])
|
||
|
|
return result, nil
|
||
|
|
}
|