c3a23b28 by astaxie

beego: improve the RandomCreateBytes #620

when rand.Read is failed. will use the math/rand to generate the rand
bytes
1 parent 9083927c
...@@ -8,18 +8,32 @@ package utils ...@@ -8,18 +8,32 @@ package utils
8 8
9 import ( 9 import (
10 "crypto/rand" 10 "crypto/rand"
11 r "math/rand"
12 "time"
11 ) 13 )
12 14
13 // RandomCreateBytes generate random []byte by specify chars. 15 // RandomCreateBytes generate random []byte by specify chars.
14 func RandomCreateBytes(n int, alphabets ...byte) []byte { 16 func RandomCreateBytes(n int, alphabets ...byte) []byte {
15 const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 17 const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
16 var bytes = make([]byte, n) 18 var bytes = make([]byte, n)
17 rand.Read(bytes) 19 var randby bool
20 if num, err := rand.Read(bytes); num != n || err != nil {
21 r.Seed(time.Now().UnixNano())
22 randby = true
23 }
18 for i, b := range bytes { 24 for i, b := range bytes {
19 if len(alphabets) == 0 { 25 if len(alphabets) == 0 {
20 bytes[i] = alphanum[b%byte(len(alphanum))] 26 if randby {
27 bytes[i] = alphanum[r.Intn(len(alphanum))]
28 } else {
29 bytes[i] = alphanum[b%byte(len(alphanum))]
30 }
21 } else { 31 } else {
22 bytes[i] = alphabets[b%byte(len(alphabets))] 32 if randby {
33 bytes[i] = alphabets[r.Intn(len(alphabets))]
34 } else {
35 bytes[i] = alphabets[b%byte(len(alphabets))]
36 }
23 } 37 }
24 } 38 }
25 return bytes 39 return bytes
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!