55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
package uniqueid
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// GenerateID 生成UUID v1作为主键
|
|
func GenerateID() string {
|
|
uuidV1, err := uuid.NewUUID()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return uuidV1.String()
|
|
}
|
|
|
|
// GenerateName 生成随机用户名
|
|
func GenerateName(prefix string) string {
|
|
str := uuid.New().String()
|
|
return prefix + str[6:12]
|
|
}
|
|
|
|
// GenerateRandomCode 生成随机码(如邀请码)
|
|
func GenerateRandomCode(length int) string {
|
|
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
var sb strings.Builder
|
|
for i := 0; i < length; i++ {
|
|
n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
|
sb.WriteByte(charset[n.Int64()])
|
|
}
|
|
return sb.String()
|
|
}
|
|
|
|
// GenCodeKey 生成邀请码的Redis Key
|
|
func GenCodeKey(userID string) string {
|
|
return fmt.Sprintf("code:%s", userID)
|
|
}
|
|
|
|
// GenOrderNo 生成订单号
|
|
func GenOrderNo() string {
|
|
now := time.Now()
|
|
timePart := now.Format("20060102150405")
|
|
machineID := 1
|
|
pid := now.Nanosecond() % 1000
|
|
businessPart := fmt.Sprintf("%02d%03d%01d", machineID, pid, now.Second()%10)
|
|
random1 := fmt.Sprintf("%04d", now.Nanosecond()%10000)
|
|
random2 := fmt.Sprintf("%04d", (now.Nanosecond()/10000)%10000)
|
|
return timePart + businessPart + random1 + random2
|
|
}
|