package utils import ( "math/rand" "simple-memo/global" "simple-memo/models" "time" ) const userCodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" func init() { rand.Seed(time.Now().UnixNano()) } func GenerateUserCode() string { for { code := generateRandomCode(8) if isUserCodeUnique(code) { return code } } } func generateRandomCode(length int) string { result := make([]byte, length) for i := range result { result[i] = userCodeChars[rand.Intn(len(userCodeChars))] } return string(result) } func isUserCodeUnique(code string) bool { var count int64 global.DB.Model(&models.User{}).Where("user_code = ?", code).Count(&count) return count == 0 }