Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

≋ Lothal

A lightweight HTTP server built from scratch in C++ using WinSock.

Built from the socket up.

A production-grade HTTP/1.1 web server written completely from scratch in Modern C++ using WinSock.

No web frameworks. No HTTP libraries. Every layer—from TCP sockets to routing, middleware, caching, compression, and streaming—was engineered by hand to understand how the web works beneath the abstractions.

🌍 Live Demo

Lothal serves its own documentation website.

Explore the architecture, inspect HTTP requests, and interact with live demonstrations of every implemented feature.

🔗 Documentation & Interactive Demo https://lothal.its_currently_not_live.com

Every page of this website is served by Lothal itself.

🚢 Interactive Documentation

Unlike traditional documentation, Lothal's website is itself part of the project.

Visitors can:

  • Send real HTTP requests
  • Watch request lifecycles
  • Compare Gzip compression
  • Test caching (ETag / 304)
  • Stream videos using Range Requests
  • Trigger rate limiting
  • Explore middleware execution
  • Visualize routing

Current Features

  • TCP Socket
  • HTTP Request Handling
  • Basic HTTP Response
  • Request Logging
  • HTTP Parser
  • Static File Server
  • MIME Types
  • Binary File Support
  • Routing
  • Middleware Pipeline
  • Multithreading
  • Keep Alive
  • Range Requests
  • Compression
  • Chunked
  • Caching
  • Configuration
  • Logging

Planned Features

  • Directory Listing
  • Virtual Hosts
  • IOCP
  • RFC Compliance
  • HTTPS

Learning Goals

This project is being built to understand:

  • TCP/IP Networking
  • Socket Programming
  • HTTP Protocol
  • Web Server Architecture =======

≋ Lothal v1.0.0 — Modern C++ HTTP/1.1 Server

C++20 Platform License GitHub

"If the Harappan Civilization built a modern software web server."

Lothal is a production-style, multithreaded HTTP/1.1 web server written completely from scratch in Modern C++ using raw WinSock (Windows Sockets). Zero external HTTP or web frameworks were used.

It is designed with production-grade software architecture, fulfilling two goals simultaneously:

  1. Explains internal web server engineering from raw socket bytes to high-level middleware pipelines.
  2. Hosts its own interactive demonstration website, allowing visitors to inspect every protocol feature live in real-time.

📖 Complete Documentation Index

For exhaustive technical guides, API references, architecture breakdowns, and contribution manuals, check out:


🏛️ The Name & Philosophy

Named after Lothal (2400 BCE), one of the world's earliest known port cities built by the Indus Valley Civilization in present-day Gujarat, India. Its dockyards, granaries, channels, and trade routes regulated commerce across ancient civilizations.

An HTTP server performs a surprisingly similar role: requests arrive at the harbor, are inspected at the watchtower, routed through channels, processed in workshops, and dispatched back across the network.


✨ Feature Matrix

Feature Implementation Architecture Highlight
Core Network Native WinSock2 (server.cpp, socket.cpp) Non-blocking socket listener dispatching to thread pool
Concurrency Custom Thread Pool (ThreadPool.cpp) Pre-allocated worker thread pool with mutex & condition variable queue
Parsing Direct HTTP/1.1 Parser (HttpRequest.cpp) Single-pass request line, headers, query string, and body parsing
Response Engine Response Builder (HttpResponse.cpp) Zero-copy header building, custom status codes, MIME resolution
Routing Dynamic Regex Router (router.cpp) Startup compilation of patterns (/users/:id), priority sorting
Middleware Chain Chain of Responsibility (MiddlewarePipeline.cpp) Sequential pipeline execution with abort-on-error capabilities
RAM Cache & ETag In-Memory File Cache (FileCache.cpp) ETag hashing & If-None-Match handling returning 304 Not Modified
Compression Dynamic Gzip (Compression.cpp) zlib-based gzip compression for clients sending Accept-Encoding: gzip
Streaming Chunked Transfer (ChunkedResponse.cpp) Transfer-Encoding: chunked for live data streams without fixed size
Partial Content Byte Range Requests (HttpRange.cpp) RFC 7233 byte range parsing returning 206 Partial Content
Keep-Alive Persistent TCP Connections Socket reuse across request loops with configurable timeout
Security Gate Sliding-Window Rate Limiter (RateLimitMiddleware.cpp) IP-based request throttling returning 429 Too Many Requests
Authentication Bearer Token Middleware (AuthMiddleware.cpp) Route protection for /api/* endpoints requiring Bearer tokens
CORS Cross-Origin Middleware (CorsMiddleware.cpp) Automatic OPTIONS preflight handling and header injection
Fault Tolerance Top-Level Guard (ExceptionMiddleware.cpp) Catches runtime C++ exceptions, preventing worker crashes (500 Error)

🛠️ Architecture & Request Lifecycle

Browser (Client)
    │
    ▼  TCP SYN → SYN-ACK → ACK
WinSock accept()          ← server.cpp (Server::start)
    │
    ▼  Dispatched to worker thread queue
ThreadPool::enqueue()     ← ThreadPool.cpp
    │
    ▼  recv() raw byte stream
HttpRequest::parse()      ← HttpRequest.cpp
    │
    ▼  Sequential execution chain
MiddlewarePipeline::run() ← MiddlewarePipeline.cpp
    │
    ├── ExceptionMiddleware   (Top-level try/catch guard)
    ├── StaticFileMiddleware  (Serves /public/ from RAM cache or disk)
    ├── LoggerMiddleware      (Logs timestamp, IP, method, status, duration)
    ├── CorsMiddleware        (Injects CORS headers & handles OPTIONS)
    ├── AuthMiddleware        (Validates Authorization: Bearer tokens for /api/*)
    └── RateLimitMiddleware   (Sliding window rate check per client IP)
    │
    ▼  Matches path against compiled regex routes
Router::handle()          ← router.cpp (RouteCompiler & RouteMatcher)
    │
    ▼  Executes endpoint logic
HttpResponse::build()     ← HttpResponse.cpp
    │
    ├── Gzip Compression      (If Accept-Encoding: gzip enabled)
    ├── Chunked Encoding       (If setChunked(true))
    ├── ETag / 304 Evaluation  (If-None-Match header match)
    └── Range Resolution      (Range: bytes=X-Y -> 206 Partial Content)
    │
    ▼  send() formatted HTTP bytes over Winsock
Keep-Alive Connection Check -> Re-loop or Close Socket

🚀 Quick Start & Building

Prerequisites

  • OS: Windows 10 / 11
  • Compiler: MinGW-w64 (g++ supporting C++20) or MSVC
  • Libraries: ws2_32 (WinSock), z (zlib)

Build with MinGW (GCC / g++)

g++ -std=c++20 -O2 -Wall -o lothal.exe main.cpp server.cpp HttpRequest.cpp HttpResponse.cpp router.cpp RouteCompiler.cpp RouteMatcher.cpp RouteSorter.cpp MiddlewarePipeline.cpp Middleware.cpp ThreadPool.cpp FileCache.cpp FileSystem.cpp Compression.cpp ChunkedResponse.cpp ETag.cpp LastModified.cpp MimeTypes.cpp Logger.cpp StaticFileMiddleware.cpp AuthMiddleware.cpp LoggerMiddleware.cpp CorsMiddleware.cpp RateLimitMiddleware.cpp ExceptionMiddleware.cpp Config.cpp route.cpp HttpRange.cpp HttpRangeResolver.cpp RequestInspector.cpp -lws2_32 -lz

Run Lothal

.\lothal.exe

Output:

[INFO] ThreadPool initialized with 4 workers
========== LOTHAL ==========
Port         : 8080
Document Root: public
Threads      : 4
Keep-Alive   : 1
Cache        : 1
Gzip         : 1
============================
[INFO] Winsock initialized!
[INFO] Listening on port 8080
[INFO] Server started

Open your browser and visit http://localhost:8080.


⚙️ Configuration (lothal.conf)

Lothal reads configuration key-value pairs at startup:

# Lothal Server Configuration
port=8080
threads=4
document_root=public
keep_alive=1
keep_alive_timeout=10
cache_enabled=1
gzip_enabled=1
max_rate_limit=500
rate_window_sec=10

🌐 Endpoints Provided by Lothal Demo

Route Method Description
/ GET Serves the interactive Lothal documentation web application
/api/hello GET Health check endpoint returning status JSON
/api/echo GET, HEAD, OPTIONS Request inspection endpoint echoing back client headers
/api/resource/:id GET, PUT, PATCH, DELETE Demonstration of RESTful HTTP method handling
/api/search QUERY Custom HTTP method implementation demonstration
/login POST Authentication demonstration route
/users/:id GET Dynamic route parameter extraction demo
/slow GET 5-second simulated latency route for thread pool concurrency testing
/stream GET 100-chunk Transfer-Encoding streaming demonstration
/crash GET Controlled C++ exception route testing fault recovery

👤 Author & Credits

Created with passion by Shantanu Gopal Vispute:


📜 License

Distributed under the MIT License. See LICENSE for details.

533286e (Lothal v-1)

About

An http server

Resources

Contributing

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages