github.com/astaxie/beego@v1.12.3/utils/rand.go (about)

     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  
    15  package utils
    16  
    17  import (
    18  	"crypto/rand"
    19  	r "math/rand"
    20  	"time"
    21  )
    22  
    23  var alphaNum = []byte(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`)
    24  
    25  // RandomCreateBytes generate random []byte by specify chars.
    26  func RandomCreateBytes(n int, alphabets ...byte) []byte {
    27  	if len(alphabets) == 0 {
    28  		alphabets = alphaNum
    29  	}
    30  	var bytes = make([]byte, n)
    31  	var randBy bool
    32  	if num, err := rand.Read(bytes); num != n || err != nil {
    33  		r.Seed(time.Now().UnixNano())
    34  		randBy = true
    35  	}
    36  	for i, b := range bytes {
    37  		if randBy {
    38  			bytes[i] = alphabets[r.Intn(len(alphabets))]
    39  		} else {
    40  			bytes[i] = alphabets[b%byte(len(alphabets))]
    41  		}
    42  	}
    43  	return bytes
    44  }