Skip to content

secus217/rush-backend-template

Repository files navigation

🦀 Rust Backend Template with Axum

A clean, scalable, and production-ready backend template built with Rust and Axum framework.

✨ Features

  • 🚀 Axum Framework - Fast, ergonomic web framework
  • 🏗️ Clean Architecture - Layered architecture with handlers, services, and repositories
  • 🔒 JWT Authentication - Secure user authentication and authorization
  • 🗄️ PostgreSQL Integration - Database operations with SQLx
  • 🔧 Configuration Management - Environment-based configuration
  • 📝 Comprehensive Logging - Structured logging with tracing
  • 🐳 Docker Support - Full containerization with Docker Compose
  • 🧪 Testing Framework - Unit and integration tests
  • 📊 Health Checks - Application health monitoring
  • 🌐 CORS Support - Cross-origin resource sharing
  • 📦 Error Handling - Comprehensive error handling system
  • 📖 Swagger UI - Interactive API documentation with OpenAPI 3.0

🏗️ Project Structure

rust-backend-template/
├── src/
│   ├── handlers/          # HTTP request handlers
│   │   ├── auth.rs        # Authentication endpoints
│   │   ├── health.rs      # Health check endpoint
│   │   ├── users.rs       # User CRUD endpoints
│   │   └── mod.rs
│   ├── services/          # Business logic layer
│   │   ├── user.rs        # User business logic
│   │   └── mod.rs
│   ├── repositories/      # Data access layer
│   │   ├── user.rs        # User database operations
│   │   └── mod.rs
│   ├── models/            # Data models and DTOs
│   │   ├── user.rs        # User models
│   │   └── mod.rs
│   ├── middleware/        # Custom middleware
│   │   ├── auth.rs        # Authentication middleware
│   │   └── mod.rs
│   ├── utils/             # Utility functions
│   │   ├── database.rs    # Database utilities
│   │   ├── jwt.rs         # JWT utilities
│   │   ├── password.rs    # Password hashing
│   │   └── mod.rs
│   ├── config.rs          # Configuration management
│   ├── errors.rs          # Error types and handling
│   ├── swagger.rs         # Swagger/OpenAPI configuration
│   └── main.rs            # Application entry point
├── migrations/            # Database migrations
├── tests/                 # Integration tests
├── docker-compose.yml     # Docker services
├── Dockerfile             # Container definition
├── deploy.sh              # Deployment script
└── README.md

🚀 Quick Start

Prerequisites

  • Rust 1.75+
  • PostgreSQL 15+
  • Docker & Docker Compose (optional)

Option 1: Docker Setup (Recommended)

  1. Clone the repository

    git clone <your-repo-url>
    cd rust-backend-template
  2. Run with Docker

    ./deploy.sh

    This will:

    • Build the application
    • Start PostgreSQL and Redis
    • Run database migrations
    • Start the backend server
  3. Access the API

Option 2: Local Development

  1. Setup Environment

    cp .env.example .env
    # Edit .env with your configuration
  2. Start PostgreSQL

    docker run --name postgres -e POSTGRES_PASSWORD=password -e POSTGRES_DB=rust_backend -p 5432:5432 -d postgres:15
  3. Run Migrations

    cargo install sqlx-cli
    sqlx migrate run
  4. Start the Application

    cargo run

📡 API Endpoints

Public Endpoints

Method Endpoint Description
GET /api/v1/health Health check
POST /api/v1/auth/register Register new user
POST /api/v1/auth/login Login user

Protected Endpoints (Require JWT Token)

Method Endpoint Description
GET /api/v1/users/me Get current user
PUT /api/v1/users/me Update current user
DELETE /api/v1/users/me Delete current user
GET /api/v1/users List all users
GET /api/v1/users/:id Get user by ID
PUT /api/v1/users/:id Update user by ID
DELETE /api/v1/users/:id Delete user by ID

🔐 Authentication

The API uses JWT (JSON Web Tokens) for authentication.

Register a new user

curl -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "password123",
    "full_name": "John Doe"
  }'

Login

curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "password123"
  }'

Use JWT Token

curl -X GET http://localhost:3000/api/v1/users/me \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

📖 API Documentation

Swagger UI

The API comes with interactive Swagger UI documentation:

Features:

  • 🔍 Interactive API explorer
  • 🔐 Built-in JWT authentication testing
  • 📝 Request/response examples
  • 🎯 Try-it-out functionality
  • 📋 Model schemas with validation rules

To use protected endpoints in Swagger:

  1. Register/Login to get a JWT token
  2. Click "Authorize" button in Swagger UI
  3. Enter: Bearer YOUR_JWT_TOKEN
  4. Now you can test protected endpoints

⚙️ Configuration

The application is configured through environment variables:

Variable Description Default
DATABASE_URL PostgreSQL connection string postgresql://localhost:5432/rust_backend
JWT_SECRET Secret key for JWT signing your-super-secret-jwt-key
JWT_EXPIRES_IN JWT expiration time 24h
PORT Server port 3000
CORS_ORIGIN CORS allowed origins *
ENVIRONMENT Runtime environment development
LOG_LEVEL Logging level info

🧪 Testing

Run Unit Tests

cargo test

Run Integration Tests

# Setup test database
export DATABASE_URL=postgresql://localhost:5432/rust_backend_test
sqlx database create
sqlx migrate run

# Run tests
cargo test --test integration_tests

🐳 Docker Commands

# Build and start all services
docker-compose up --build -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

# Restart services
docker-compose restart

# Execute commands in container
docker-compose exec backend bash

📊 Database Migrations

# Install SQLx CLI
cargo install sqlx-cli

# Create new migration
sqlx migrate add create_users_table

# Run migrations
sqlx migrate run

# Revert last migration
sqlx migrate revert

🔧 Development

Adding New Features

  1. Create Model in src/models/
  2. Create Repository in src/repositories/
  3. Create Service in src/services/
  4. Create Handlers in src/handlers/
  5. Add Routes to main router
  6. Write Tests in tests/

Code Quality

# Format code
cargo fmt

# Lint code
cargo clippy

# Check for security vulnerabilities
cargo audit

🚀 Deployment

Production Deployment

  1. Build optimized image

    docker build -t rust-backend:prod .
  2. Set production environment variables

    export ENVIRONMENT=production
    export JWT_SECRET=your-production-secret
    export DATABASE_URL=your-production-db-url
  3. Deploy with docker-compose

    docker-compose -f docker-compose.prod.yml up -d

Health Checks

The application includes health checks at /api/v1/health that return:

{
  "status": "ok",
  "message": "Service is healthy",
  "timestamp": "2023-10-01T12:00:00Z"
}

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Axum - Web framework
  • SQLx - Database toolkit
  • Tokio - Async runtime
  • Serde - Serialization framework

Happy coding! 🦀✨

rush-backend-template

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published