A simple and efficient URL shortening library implemented in Python and Go.
- Shorten URLs with multiple algorithms (hash-based, random)
- Expand short codes back to original URLs
- Click statistics tracking
- Thread-safe operations (Go implementation)
- Duplicate detection - same URL returns same short code
- Simple API - easy to use
- Python (3.9, 3.10, 3.11)
- Go (1.20, 1.21, 1.22)
cd python
pip install -r requirements.txtcd go
go mod downloadfrom url_shortener import URLShortener
# Create shortener instance
shortener = URLShortener()
# Shorten a URL (hash method)
short_code = shortener.shorten("https://www.example.com/very/long/url", method="hash")
print(f"Short code: {short_code}")
# Shorten a URL (random method)
short_code = shortener.shorten("https://www.example.com/another/url", method="random")
# Expand short code
original_url = shortener.expand(short_code)
print(f"Original URL: {original_url}")
# Get statistics
clicks = shortener.get_stats(short_code)
print(f"Clicks: {clicks}")package main
import (
"fmt"
"github.com/yourusername/urlshortener"
)
func main() {
// Create shortener instance
shortener := urlshortener.NewURLShortener()
// Shorten a URL (hash method)
shortCode, err := shortener.Shorten("https://www.example.com/very/long/url", "hash")
if err != nil {
panic(err)
}
fmt.Printf("Short code: %s\n", shortCode)
// Expand short code
originalURL, exists := shortener.Expand(shortCode)
if exists {
fmt.Printf("Original URL: %s\n", originalURL)
}
// Get statistics
clicks, exists := shortener.GetStats(shortCode)
if exists {
fmt.Printf("Clicks: %d\n", clicks)
}
}Create a new URLShortener instance.
Shorten a long URL.
- Parameters:
long_url: The URL to shortenmethod: Either "hash" or "random" (default: "hash")
- Returns: Short code string
- Raises:
ValueErrorif URL is empty or method is invalid
Expand a short code to its original URL.
- Parameters:
short_code: The shortened code
- Returns: Original URL or None if not found
Get click statistics for a short code.
- Parameters:
short_code: The shortened code
- Returns: Number of clicks or None if not found
Create a new URLShortener instance.
Shorten a long URL.
- Parameters:
longURL: The URL to shortenmethod: Either "hash" or "random"
- Returns: Short code and error (if any)
Expand a short code to its original URL.
- Parameters:
shortCode: The shortened code
- Returns: Original URL and existence flag
Get click statistics for a short code.
- Parameters:
shortCode: The shortened code
- Returns: Number of clicks and existence flag
cd python
python -m pytest test_url_shortener.py -vcd go
go test -v- Uses MD5 hash of the URL
- Takes first 6 characters of the hash
- Same URL always produces the same short code
- Fast and deterministic
- Generates random 6-character code
- Uses alphanumeric characters (a-z, A-Z, 0-9)
- Checks for collisions before assignment
- Different code each time (unless URL already shortened)