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.
- Express-like routing & middleware architecture
- Threadpool for handling concurrent requests
- Built-in static file-serving with directory traversal prevention
- MIME type auto-detection
- Full HTTP/1.0 compliance (POST support)
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;
}- C++17
- CMake 3.11+
mkdir build && cd build
cmake ..
cmake --build .