Skip to content

secus217/rush-backend-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

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

 
 
 

Contributors