You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
616 B
Go
35 lines
616 B
Go
package generate
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"math/big"
|
|
)
|
|
|
|
// GetRandomString 取得隨機字串
|
|
func GetRandomString(n int) (string, error) {
|
|
const alphaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
|
|
buffer := make([]byte, n)
|
|
max := big.NewInt(int64(len(alphaNum)))
|
|
|
|
for i := 0; i < n; i++ {
|
|
index, err := randomInt(max)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
buffer[i] = alphaNum[index]
|
|
}
|
|
|
|
return string(buffer), nil
|
|
}
|
|
|
|
func randomInt(max *big.Int) (int, error) {
|
|
random, err := rand.Int(rand.Reader, max)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return int(random.Int64()), nil
|
|
}
|