github.com/godaddy-x/freego@v1.0.156/utils/gorand.go (about) 1 package utils 2 3 import ( 4 "math/rand" 5 _ "unsafe" 6 ) 7 8 const numbers = "0123456789" 9 const letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 10 const lettersSp = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*" 11 12 //go:linkname fastrand runtime.fastrand 13 func fastrand() uint32 14 15 func gorand(n int, characters string) string { 16 randomString := make([]byte, n) 17 for i := range randomString { 18 randomString[i] = characters[rand.Intn(len(characters))] 19 } 20 return Bytes2Str(randomString) 21 } 22 23 func RandStr(n int, b ...bool) string { 24 if len(b) > 0 { 25 return gorand(n, lettersSp) 26 } 27 return gorand(n, letters) 28 } 29 30 func RandInt(n int) string { 31 return gorand(n, numbers) 32 } 33 34 func RandNonce() string { 35 return RandStr(8) 36 } 37 38 // ModRand 调用底层生成随机数,进行取模运算,性能提升10倍 39 func ModRand(n int) int { 40 return int(fastrand() % uint32(n)) 41 }