package common import ( "crypto/rand" "math/big" ) // Rand 生成指定长度的随机字符串,字符集为 [0-9a-zA-Z] // 使用 crypto/rand 保证不可预测性 func Rand(length int) string { const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" b := make([]byte, length) max := big.NewInt(int64(len(charset))) for i := range b { n, err := rand.Int(rand.Reader, max) if err != nil { // crypto/rand 不应失败,如果失败说明系统随机源有问题 panic("crypto/rand failed: " + err.Error()) } b[i] = charset[n.Int64()] } return string(b) } // RandFloat64 返回 [0.0,1.0) 范围的随机浮点数 // 使用 crypto/rand 保证不可预测性 func RandFloat64() float64 { n, err := rand.Int(rand.Reader, big.NewInt(1<<53)) if err != nil { panic("crypto/rand failed: " + err.Error()) } return float64(n.Int64()) / float64(1<<53) }