beego: improve the RandomCreateBytes #620
when rand.Read is failed. will use the math/rand to generate the rand bytes
Showing
1 changed file
with
15 additions
and
1 deletions
| ... | @@ -8,19 +8,33 @@ package utils | ... | @@ -8,19 +8,33 @@ 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 { |
| 26 | if randby { | ||
| 27 | bytes[i] = alphanum[r.Intn(len(alphanum))] | ||
| 28 | } else { | ||
| 20 | bytes[i] = alphanum[b%byte(len(alphanum))] | 29 | bytes[i] = alphanum[b%byte(len(alphanum))] |
| 30 | } | ||
| 31 | } else { | ||
| 32 | if randby { | ||
| 33 | bytes[i] = alphabets[r.Intn(len(alphabets))] | ||
| 21 | } else { | 34 | } else { |
| 22 | bytes[i] = alphabets[b%byte(len(alphabets))] | 35 | bytes[i] = alphabets[b%byte(len(alphabets))] |
| 23 | } | 36 | } |
| 24 | } | 37 | } |
| 38 | } | ||
| 25 | return bytes | 39 | return bytes |
| 26 | } | 40 | } | ... | ... |
-
Please register or sign in to post a comment