This project is a URL shortener service built with Rust, Warp, PostgreSQL, and Redis. It allows users to shorten long URLs and redirect to the original URLs using the shortened links.
- Shorten long URLs
- Redirect to original URLs using shortened links
- Rate limiting to prevent abuse
- Input validation to prevent malicious URLs
- Caching with Redis for faster redirects
- Rust (latest stable version)
- PostgreSQL
- Redis
- Docker (optional, for running PostgreSQL and Redis in containers)
git clone https://github.com/codewithwan/rust-url-shortener.git
cd rust-url-shortener
You can either install PostgreSQL and Redis locally or use Docker to run containers.
docker run --name url-shortener-db -e POSTGRES_PASSWORD=your_password -e POSTGRES_DB=shortlink -p 5432:5432 -d postgres
docker run --name url-shortener-redis -p 6379:6379 -d redis
Install PostgreSQL and Redis, then create a database named shortlink
.
Create a .env
file in the root directory with the following content:
# PostgreSQL
POSTGRES_USER=your_postgres_user
POSTGRES_PASSWORD=your_postgres_password
POSTGRES_DB=your_postgres_db
DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}
# Redis
REDIS_URL=redis://localhost:6379
# Application
BASE_URL=http://localhost:3030
RUST_ENV=development
PORT=3030
Alternatively, you can use the provided .env.example
file as a template:
cp .env.example .env
Create the shortlink
table in your PostgreSQL database:
CREATE TABLE shortlink (
id SERIAL PRIMARY KEY,
short_code VARCHAR(8) NOT NULL UNIQUE,
original_url TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Alternatively, you can use the provided SQL migration file:
psql -U postgres -d shortlink -f migrations/2025-02-14-create-shortlink-table.sql
cargo build
cargo run
The server will start running at http://localhost:3030
.
Send a POST request to /shorten
with a JSON body containing the URL to be shortened.
curl -X POST http://localhost:3030/shorten -H "Content-Type: application/json" -d '{"url": "https://example.com"}'
Access the shortened URL in your browser or send a GET request to the shortened URL.
curl http://localhost:3030/<short_code>
This project is licensed under the MIT License.