app-cloudep-member-server/pkg/usecase/generate_verify_code_utils.go

33 lines
669 B
Go
Raw Normal View History

2024-12-30 03:58:14 +00:00
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
}