29 lines
696 B
Go
29 lines
696 B
Go
package common
|
|
|
|
import "crypto/rand"
|
|
|
|
// UuidV4 生成 UUIDv4 字符串(crypto/rand 16 字节 + 版本/变体位,无第三方依赖);
|
|
// 用于封面等文件名,避免固定命名碰撞。
|
|
func UuidV4() string {
|
|
var b [16]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
panic(err) // crypto/rand 失败属系统级故障,直接崩溃重启
|
|
}
|
|
b[6] = (b[6] & 0x0f) | 0x40 // version 4
|
|
b[8] = (b[8] & 0x3f) | 0x80 // variant 10
|
|
const hex = "0123456789abcdef"
|
|
out := make([]byte, 36)
|
|
j := 0
|
|
for i := 0; i < 16; i++ {
|
|
if i == 4 || i == 6 || i == 8 || i == 10 {
|
|
out[j] = '-'
|
|
j++
|
|
}
|
|
out[j] = hex[b[i]>>4]
|
|
j++
|
|
out[j] = hex[b[i]&0x0f]
|
|
j++
|
|
}
|
|
return string(out)
|
|
}
|