StoreShortLink stores a short link in the database with optimized collision handling
(shortCode string, originalURL string)
| 412 | |
| 413 | // StoreShortLink stores a short link in the database with optimized collision handling |
| 414 | func StoreShortLink(shortCode string, originalURL string) error { |
| 415 | shortLink := ShortLink{ |
| 416 | ShortCode: shortCode, |
| 417 | OriginalURL: originalURL, |
| 418 | } |
| 419 | |
| 420 | // Try direct insert first with DO NOTHING on conflict |
| 421 | result := db.Clauses(clause.OnConflict{ |
| 422 | DoNothing: true, |
| 423 | }).Create(&shortLink) |
| 424 | |
| 425 | if result.Error != nil { |
| 426 | return result.Error |
| 427 | } |
| 428 | |
| 429 | // If no rows were affected, either there was a shortCode collision or the URL exists |
| 430 | if result.RowsAffected == 0 { |
| 431 | // Check if URL already exists |
| 432 | var existing ShortLink |
| 433 | if err := db.Where("original_url = ?", originalURL).First(&existing).Error; err == nil { |
| 434 | return nil // URL exists, reuse existing shortcode |
| 435 | } |
| 436 | |
| 437 | // Handle collision with simple numeric suffixes |
| 438 | for i := 0; i < 10; i++ { |
| 439 | newCode := fmt.Sprintf("%s%d", shortCode[:7], i) |
| 440 | shortLink.ShortCode = newCode |
| 441 | result = db.Clauses(clause.OnConflict{ |
| 442 | DoNothing: true, |
| 443 | }).Create(&shortLink) |
| 444 | |
| 445 | if result.Error == nil && result.RowsAffected > 0 { |
| 446 | return nil |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | // If simple attempts failed, try timestamp-based suffix |
| 451 | newCode := fmt.Sprintf("%s%x", shortCode[:7], time.Now().UnixNano()%16) |
| 452 | shortLink.ShortCode = newCode |
| 453 | result = db.Clauses(clause.OnConflict{ |
| 454 | DoNothing: true, |
| 455 | }).Create(&shortLink) |
| 456 | |
| 457 | if result.Error == nil && result.RowsAffected > 0 { |
| 458 | return nil |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | return nil |
| 463 | } |
| 464 | |
| 465 | // GetOriginalURL retrieves the original URL from the database using the short code |
| 466 | func GetOriginalURL(shortCode string) (string, error) { |