33 lines
669 B
Go
33 lines
669 B
Go
package usecase
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"math/big"
|
|
"strconv"
|
|
)
|
|
|
|
func generateVerifyCode(digits int) (string, error) {
|
|
// 預設為六位數
|
|
if digits <= 0 {
|
|
digits = 6
|
|
}
|
|
|
|
// 計算最大值 (10^digits - 1)
|
|
exp := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(digits)), nil)
|
|
// 生成隨機數
|
|
randomNumber, err := rand.Int(rand.Reader, exp)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// 將隨機數轉換為 string
|
|
verifyCode := strconv.Itoa(int(randomNumber.Int64()))
|
|
// 如果隨機數的位數少於指定的位數,則補 0
|
|
if len(verifyCode) < digits {
|
|
verifyCode = fmt.Sprintf("%0*d", digits, randomNumber)
|
|
}
|
|
|
|
return verifyCode, nil
|
|
}
|