Files
go-account-register/utils/index.go
2025-09-30 11:19:39 +08:00

94 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package utils
import (
"math/rand"
"strings"
"time"
"github.com/pquerna/otp/totp"
)
type RandDateParams struct {
Year int
Month int
Day int
}
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const (
letterBits = 6 // 52个字母需6位2^6=64
letterMask = 1<<letterBits - 1 // 二进制掩码63个1
)
func BoolToInt(b bool) int64 {
if b {
return 1
}
return 0
}
func RandString(n int) string {
b := make([]byte, n)
for i := 0; i < n; {
if idx := int(rand.Int63() & letterMask); idx < len(letters) {
b[i] = letters[idx]
i++
} // 丢弃无效索引,重试
}
return string(b)
}
func RandDate(minAge, maxAge int) RandDateParams {
// 创建本地随机生成器(避免全局 rand.Seed 弃用问题)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// 计算年份范围(当前年-100岁 到 当前年-18岁
currentTime := time.Now()
currentYear := currentTime.Year()
minYear := currentYear - maxAge
maxYear := currentYear - minAge
// 生成随机年份
year := minYear + r.Intn(maxYear-minYear+1)
// 生成随机月份1-12
month := r.Intn(12) + 1
// 动态计算当月最大天数(考虑闰年)
daysInMonth := 31
switch month {
case 2: // 二月特殊处理
if (year%4 == 0 && year%100 != 0) || year%400 == 0 {
daysInMonth = 29 // 闰年
} else {
daysInMonth = 28 // 平年
}
case 4, 6, 9, 11: // 30 天的月份
daysInMonth = 30
}
// 生成随机日期1 ~ daysInMonth
day := r.Intn(daysInMonth) + 1
return RandDateParams{
Year: year,
Month: month,
Day: day,
}
}
// 获取FA2码
func GetFA2Code(secret string) (string, error) {
// 去除多余的字符串
replacer := strings.NewReplacer(
"-", "",
" ", "",
)
result := replacer.Replace(secret)
code, err := totp.GenerateCode(result, time.Now())
if err != nil {
return "", err
}
return code, nil
}