rand.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "crypto/rand"
  17. r "math/rand"
  18. "time"
  19. )
  20. var alphaNum = []byte(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`)
  21. // RandomCreateBytes generate random []byte by specify chars.
  22. func RandomCreateBytes(n int, alphabets ...byte) []byte {
  23. if len(alphabets) == 0 {
  24. alphabets = alphaNum
  25. }
  26. var bytes = make([]byte, n)
  27. var randBy bool
  28. if num, err := rand.Read(bytes); num != n || err != nil {
  29. r.Seed(time.Now().UnixNano())
  30. randBy = true
  31. }
  32. for i, b := range bytes {
  33. if randBy {
  34. bytes[i] = alphabets[r.Intn(len(alphabets))]
  35. } else {
  36. bytes[i] = alphabets[b%byte(len(alphabets))]
  37. }
  38. }
  39. return bytes
  40. }