help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
rust-web-server
/
src
RSK World
rust-web-server
Rust Web Server - High-Performance Async Web Server + WebSocket Support + JWT Authentication + File Upload + Memory Safety + Educational Design
src
  • auth.rs15.7 KB
  • config.rs2.9 KB
  • error.rs5.2 KB
  • file_upload.rs19 KB
  • handlers.rs12.8 KB
  • lib.rs1.8 KB
  • main.rs6 KB
  • middleware.rs6.2 KB
  • static_files.rs9.9 KB
  • utils.rs9.6 KB
  • websocket.rs15.3 KB
API.mdmiddleware.rs
docs/API.md
Raw Download

API.md

# API Documentation

## Overview

The Rust Web Server provides a RESTful API with endpoints for server information, health checks, statistics, and more.

## Base URL

```
http://localhost:8080
```

## Authentication

Some endpoints may require authentication. When authentication is enabled, include the JWT token in the Authorization header:

```
Authorization: Bearer <your-jwt-token>
```

## Endpoints

### Health Check

Get the current health status of the server.

**Endpoint:** `GET /health`

**Response:**
```json
{
"status": "healthy",
"timestamp": "2026-01-23T10:00:00Z",
"uptime_seconds": 3600,
"active_connections": 5
}
```

### Server Information

Get detailed information about the server.

**Endpoint:** `GET /api/info`

**Response:**
```json
{
"name": "Rust Web Server",
"version": "0.1.0",
"description": "High-performance web server built with Rust",
"author": "RSK World",
"contact": {
"website": "https://rskworld.in",
"email": "hello@rskworld.in",
"phone": "+91 93305 39277",
"address": "Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147"
},
"features": [
"High performance",
"Async request handling",
"Memory safety",
"Concurrent connections",
"Static file serving",
"Systems programming"
],
"technologies": [
"Rust",
"Tokio",
"Async/Await",
"HTTP Server",
"Memory Safety",
"Concurrency"
]
}
```

### Server Statistics

Get server performance statistics and metrics.

**Endpoint:** `GET /api/stats`

**Response:**
```json
{
"uptime_seconds": 3600,
"request_count": 1250,
"active_connections": 5,
"memory_usage_mb": 42.0,
"cpu_usage_percent": 15.2,
"total_requests": 1250,
"avg_response_time_ms": 12.5
}
```

### Echo Service

Echo back the request data with additional metadata.

**Endpoint:** `POST /api/echo`

**Request Body:**
```json
{
"message": "Hello, World!",
"user": "test-user"
}
```

**Response:**
```json
{
"message": "Hello, World!",
"user": "test-user",
"timestamp": "2026-01-23T10:00:00Z",
"method": "POST",
"path": "/api/echo",
"headers": {
"content-type": "application/json",
"user-agent": "curl/7.68.0"
}
}
```

### File Upload

Upload files to the server.

**Endpoint:** `POST /api/upload`

**Content-Type:** `multipart/form-data`

**Parameters:**
- `file`: The file to upload

**Response:**
```json
{
"filename": "uploaded_file.txt",
"original_filename": "document.txt",
"size": 1024,
"content_type": "text/plain",
"upload_time": "2026-01-23T10:00:00Z",
"url": "/uploads/uploaded_file.txt"
}
```

### Authentication Endpoints

#### Login

**Endpoint:** `POST /api/auth/login`

**Request Body:**
```json
{
"username": "admin",
"password": "password"
}
```

**Response:**
```json
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"user": {
"id": "user-123",
"username": "admin",
"email": "admin@example.com",
"role": "Admin"
},
"expires_at": "2026-01-23T11:00:00Z"
}
```

#### Register

**Endpoint:** `POST /api/auth/register`

**Request Body:**
```json
{
"username": "newuser",
"email": "user@example.com",
"password": "securepassword"
}
```

**Response:**
```json
{
"message": "User registered successfully",
"user_id": "user-456"
}
```

## Error Responses

All API endpoints return appropriate HTTP status codes and error messages:

### 400 Bad Request
```json
{
"error": "Bad Request",
"message": "Invalid request parameters",
"details": "The 'username' field is required"
}
```

### 401 Unauthorized
```json
{
"error": "Unauthorized",
"message": "Authentication required"
}
```

### 403 Forbidden
```json
{
"error": "Forbidden",
"message": "Access denied"
}
```

### 404 Not Found
```json
{
"error": "Not Found",
"message": "Endpoint not found"
}
```

### 500 Internal Server Error
```json
{
"error": "Internal Server Error",
"message": "An unexpected error occurred"
}
```

## Rate Limiting

The API implements rate limiting to prevent abuse:

- **General endpoints:** 100 requests per minute per IP
- **Authentication endpoints:** 10 requests per minute per IP
- **File upload:** 5 uploads per minute per user

Rate limit headers are included in responses:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 1642934460
```

## CORS

Cross-Origin Resource Sharing is supported. By default, the server allows requests from:
- `http://localhost:3000`
- `http://localhost:8080`

## Content Types

The API supports the following content types:
- `application/json`
- `multipart/form-data` (for file uploads)
- `text/plain`

## Versioning

The API uses URL-based versioning. The current version is v1 (no version prefix in URLs).

---

**© 2026 RSK World. All rights reserved.**
src/middleware.rs
Raw Download
Find: Go to:
/*
 * Middleware Module - Rust Web Server
 * 
 * Created by RSK World (https://rskworld.in)
 * Founder: Molla Samser
 * Designer & Tester: Rima Khatun
 * 
 * Contact:
 * - Email: hello@rskworld.in, support@rskworld.in
 * - Phone: +91 93305 39277
 * - Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
 * 
 * © 2026 RSK World. All rights reserved.
 * Content used for educational purposes only.
 */

use hyper::{Body, Request, Response};
use std::time::Instant;
use tracing::{info, warn};

/// Request logging middleware
pub async fn log_request(req: Request<Body>) -> Request<Body> {
    let method = req.method().clone();
    let uri = req.uri().clone();
    let user_agent = req.headers()
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("Unknown");

    info!("Incoming request: {} {} from {}", method, uri, user_agent);
    
    req
}

/// Response logging middleware
pub async fn log_response(
    req: &Request<Body>,
    response: &Response<Body>,
    start_time: Instant,
) {
    let method = req.method();
    let uri = req.uri();
    let status = response.status();
    let duration = start_time.elapsed();

    let status_level = if status.is_success() {
        "INFO"
    } else if status.is_client_error() {
        "WARN"
    } else if status.is_server_error() {
        "ERROR"
    } else {
        "INFO"
    };

    match status_level {
        "INFO" => info!("{} {} {} {}ms", method, uri, status, duration.as_millis()),
        "WARN" => warn!("{} {} {} {}ms", method, uri, status, duration.as_millis()),
        "ERROR" => tracing::error!("{} {} {} {}ms", method, uri, status, duration.as_millis()),
        _ => {}
    }
}

/// CORS middleware
pub fn add_cors_headers(mut response: Response<Body>) -> Response<Body> {
    let headers = response.headers_mut();
    
    headers.insert("Access-Control-Allow-Origin", "*".parse().unwrap());
    headers.insert("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS".parse().unwrap());
    headers.insert("Access-Control-Allow-Headers", "Content-Type, Authorization".parse().unwrap());
    headers.insert("Access-Control-Max-Age", "86400".parse().unwrap());
    
    response
}

/// Security headers middleware
pub fn add_security_headers(mut response: Response<Body>) -> Response<Body> {
    let headers = response.headers_mut();
    
    headers.insert("X-Content-Type-Options", "nosniff".parse().unwrap());
    headers.insert("X-Frame-Options", "DENY".parse().unwrap());
    headers.insert("X-XSS-Protection", "1; mode=block".parse().unwrap());
    headers.insert("Strict-Transport-Security", "max-age=31536000; includeSubDomains".parse().unwrap());
    headers.insert("Referrer-Policy", "strict-origin-when-cross-origin".parse().unwrap());
    
    response
}

/// Rate limiting middleware (simplified implementation)
pub struct RateLimiter {
    requests: std::collections::HashMap<String, u32>,
    window_start: std::time::Instant,
    window_duration: std::time::Duration,
    max_requests: u32,
}

impl RateLimiter {
    pub fn new(max_requests: u32, window_seconds: u64) -> Self {
        Self {
            requests: std::collections::HashMap::new(),
            window_start: std::time::Instant::now(),
            window_duration: std::time::Duration::from_secs(window_seconds),
            max_requests,
        }
    }

    pub fn is_allowed(&mut self, client_ip: &str) -> bool {
        // Reset window if expired
        if self.window_start.elapsed() > self.window_duration {
            self.requests.clear();
            self.window_start = std::time::Instant::now();
        }

        let count = self.requests.entry(client_ip.to_string()).or_insert(0);
        *count += 1;

        *count <= self.max_requests
    }
}

/// Request size limiting middleware
pub fn check_request_size(req: &Request<Body>, max_size: usize) -> bool {
    if let Some(content_length) = req.headers().get("content-length") {
        if let Ok(length_str) = content_length.to_str() {
            if let Ok(length) = length_str.parse::<usize>() {
                return length <= max_size;
            }
        }
    }
    true // Default to allowing if we can't determine size
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rate_limiter() {
        let mut limiter = RateLimiter::new(5, 60); // 5 requests per minute
        
        // Should allow first 5 requests
        for i in 0..5 {
            assert!(limiter.is_allowed("127.0.0.1"), "Request {} should be allowed", i + 1);
        }
        
        // Should deny 6th request
        assert!(!limiter.is_allowed("127.0.0.1"), "6th request should be denied");
    }

    #[test]
    fn test_request_size_check() {
        let mut builder = Request::builder()
            .method("POST")
            .uri("/test")
            .header("content-length", "1000");
        
        let request = builder.body(Body::empty()).unwrap();
        
        assert!(check_request_size(&request, 2000)); // Should allow
        assert!(!check_request_size(&request, 500));  // Should deny
    }

    #[test]
    fn test_cors_headers() {
        let response = Response::builder()
            .status(200)
            .body(Body::empty())
            .unwrap();
        
        let response_with_cors = add_cors_headers(response);
        
        assert_eq!(
            response_with_cors.headers().get("Access-Control-Allow-Origin").unwrap(),
            "*"
        );
        assert_eq!(
            response_with_cors.headers().get("Access-Control-Allow-Methods").unwrap(),
            "GET, POST, PUT, DELETE, OPTIONS"
        );
    }

    #[test]
    fn test_security_headers() {
        let response = Response::builder()
            .status(200)
            .body(Body::empty())
            .unwrap();
        
        let response_with_security = add_security_headers(response);
        
        assert_eq!(
            response_with_security.headers().get("X-Content-Type-Options").unwrap(),
            "nosniff"
        );
        assert_eq!(
            response_with_security.headers().get("X-Frame-Options").unwrap(),
            "DENY"
        );
    }
}
201 lines•6.2 KB
rust

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer