Skip to content

About

Basic HTTP server implementation in C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

23 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

simple-http-server-cpp

A simple HTTP server implementation in C++ with modern Express-style architecture. Supports (partially) HTTP/1.0. This project is written from scratch in C++ using POSIX sockets; and so, it only works on Mac/Linux and other POSIX-compliant operating systems.

Features

  • Express-like routing & middleware architecture
  • Threadpool for handling concurrent requests
  • Built-in static file-serving with directory traversal prevention

Known Limitations / TODO

  • MIME type auto-detection
  • Full HTTP/1.0 compliance (POST support)

Usage

See main.cpp for a demo program.

As can be seen from example code, it's very similar to Express.js in terms of syntax. Order of routes and middleware will matter, just like in Express.

#include "httpServer.h"

int main() {
    HttpServer server { "8000", "public" };

    // Custom Middleware
    server.use([](HttpRequest& req, HttpResponse& res, std::function<void()> next) {
        std::cout << "Request received: " << req.uri() << std::endl;
        next();
    });

    // Simple Route
    server.route("/hello", [](HttpRequest& req, HttpResponse& res) {
        res.setStatus(HttpStatus::Ok);
        res.send("<h1>Hello World!</h1>");
    });

    // Register the router
    server.use(server.getRouter());

    // Serve Static Files
    server.use(server.serveStatic("./public"));

    server.start();
    std::cout << "Server running on port 8000..." << std::endl;
    
    // Block main thread until user stops server
    std::cin.get();
    server.stop();

    return 0;
}

Build & Run Demo

Build requirements

  • C++17
  • CMake 3.11+

With cmake

mkdir build && cd build
cmake ..
cmake --build .

About

Basic HTTP server implementation in C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages