New
Apps 6,419Makers 6,403This week 7
Promote your app−30%
3views in
the last 30 days

libhttpserver

C++ library for creating an embedded REST HTTP server

Built with Claude Code

by etr · Unclaimed · from USUnited States · added Oct 29, 2026
no ratings0 comments

The libhttpserver reference manual

Sponsor

Tl;dr

libhttpserver is a C++20 library for building high-performance RESTful HTTP servers on top of GNU libmicrohttpd. v2.0 is a lambda-first redesign: a working server is ten lines, handlers are std::functions, responses are value-typed, and every public method is thread-safe by contract.

Features:

  • HTTP/1.1-compatible request parser
  • RESTful-oriented interface
  • Lambda-first handler API; class-form handlers (http_resource) when state is shared
  • Value-typed responses with seven factories and fluent with_* chaining
  • Cross-platform (Linux, *BSD, macOS, Windows / MSYS2-MinGW)
  • Multiple threading models (internal poll, internal select, thread pool, external loop)
  • IPv6 and dual-stack support
  • Optional TLS (HTTPS) via GnuTLS, including mTLS, SNI, and TLS-PSK
  • Optional Basic and Digest authentication (SHA-256, SHA-512/256, MD5)
  • Optional centralized authentication with path-based skip rules
  • Optional WebSocket support (requires libmicrohttpd built with WebSocket support)
  • Response shapes for every common body: string, file, iovec scatter-gather, pipe streaming, deferred callback, empty, and 401-unauthorized
  • Incremental POST processing (form-urlencoded, multipart/form-data, file uploads)
  • External event-loop integration (run, run_wait, get_fdset, add_connection)
  • Daemon introspection (bound port, active connections, listen FD)
  • Turbo mode, TCP_FASTOPEN, suppressed Date headers, configurable backlog
  • IP access control with wildcard ranges — deny list (deny_ip) and allow list (allow_ip), IPv4 & IPv6
  • Architecture contracts you can rely on: threading (DR-008 / §5.1) and error propagation (DR-009 / §5.2)

This README is a guided reference: it walks the v2.0 API surface section by section. It is comprehensive but not exhaustive — the headers under src/httpserver/ are the source of truth, and the examples/ tree contains a runnable demonstration of every feature.

For a visual mental model, see docs/architecture/: a class, relationship & filesystem map and a request lifecycle & routing flow diagram (Mermaid inline on GitHub, plus richer self-contained HTML pages).

The shortest possible server looks like this:

// Copyright 2026 Sebastiano Merlino
// libhttpserver hello-world example — the lambda form.
// Compiles in ten lines including main(), with no http_resource subclass
// and no raw-pointer ownership. Production code typically qualifies names
// explicitly; the `using namespace` here is a one-off so this file can
// document the shortest possible end-to-end demo. See shared_state.cpp
// for the class-based pattern that is appropriate when handlers must
// share mutable state.
#include <httpserver.hpp>
using namespace httpserver;  // NOLINT(build/namespaces) - keep the demo at <=10 LOC
int main() {
    webserver ws{create_webserver(8080)};
    ws.on_get("/hello", [](const http_request&) {
        return http_response::string("Hello, World!");
    });
    ws.start(true);
}

The block above is reproduced byte-for-byte from examples/hello_world.cpp; a CI gate (scripts/check-readme.sh) enforces the byte-for-byte equality.

Table of contents

Community

Appendices

  • Copying — short statement of the documentation license.
  • GNU-LGPL — the GNU Lesser General Public License (the library's code license; full text in COPYING.LESSER).
  • GNU-FDL — the GNU Free Documentation License (this manual's license; full text in LICENSE).
  • Thanks

Introduction

libhttpserver is meant to constitute an easy system to build HTTP servers in the REST fashion. It is built on top of libmicrohttpd and, like its substrate, it is a daemon library. The mission is to expose every useful HTTP capability through a simple, modern C++ API so that application code can focus on business logic rather than on the mechanics of HTTP request handling.

Design. libhttpserver is lambda-first. The shortest server is ten lines and uses no inheritance; handlers are std::function<http_response(const http_request&)>; responses are value-typed with seven factories and fluent with_* chaining; ownership of resource-form handlers is expressed in std::unique_ptr and std::shared_ptr. The class form (http_resource) is the right shape when several methods on one path share mutable state.

Two contracts are load-bearing — and both are stated explicitly in this README rather than left implicit:

  • Thread-safety (DR-008 / §5.1). Every public method on webserver is thread-safe and re-entrant from inside a handler, with two documented exceptions (stop(), ~webserver()) that deadlock if invoked from a handler thread.
  • Error propagation (DR-009 / §5.2). A handler that throws is caught by the dispatcher and routed through internal_error_handler. There is no throw-as-status idiom — to send a 404 from a handler, build it by value with http_response::empty().with_status(404).

libhttpserver decodes form bodies automatically: application/x-www-form-urlencoded and multipart/form-data are parsed into the request's argument map. Files attached to multipart uploads are exposed through http_request::get_files().

All functions are reentrant and thread-safe unless explicitly stated otherwise. Clients can also specify resource limits on overall connection count, per-IP connection count, and per-connection memory to avoid resource exhaustion.

Back to TOC

Requirements

libhttpserver can be used without any dependencies aside from libmicrohttpd.

The minimum versions required are:

  • g++ >= 11 or clang >= 13 (Apple Clang from Xcode 15+)
  • C++20 or newer
  • libmicrohttpd >= 1.0.0
  • [Optionally] for TLS (HTTPS) support, you'll need libgnutls.
  • [Optionally] to compile the code reference, you'll need doxygen.

On RHEL 9 (and derivatives), the stock GCC 11 is too old for some C++20 library features the build relies on; install the gcc-toolset-14 package and source /opt/rh/gcc-toolset-14/enable before configuring.

Additionally, for MinGW on Windows you will need:

  • libwinpthread (for MinGW-w64, if you use thread model posix you already have this)

For versions before 0.18.0, on MinGW you will need:

  • libgnurx >= 2.5.1

The test cases use libcurl but you don't need it to compile the library itself.

Please refer to the readme file for your particular distribution if there is one for important notes.

Platform Toolchain Notes
Debian 13 (trixie) GCC 14.2 Out-of-the-box
RHEL 9 gcc-toolset-14 Stock GCC 11 is too old; install the Red Hat toolset overlay
RHEL 10 GCC 14 Out-of-the-box
FreeBSD 14.x base Clang 18+ Out-of-the-box
macOS Homebrew GCC 15+ or current Apple Clang Out-of-the-box
vcpkg / Conan GCC 13+ / Clang 16+ Out-of-the-box

Back to TOC

Building and installation

libhttpserver uses the standard autotools workflow. The usual build process is:

./bootstrap
mkdir build
cd build
../configure
make
sudo make install

make check runs the test suite (unit + integration). make examples builds every program under examples/. make dist produces a portable source tarball.

ABI / packaging. SOVERSION is 2. Distributions package libhttpserver2, parallel-installable with prior major versions so applications can link the major they need side by side. There is no inline namespace and no symbol-versioning script.

Back to TOC

Optional parameters to the configure script

A complete list of parameters can be obtained by running ./configure --help. The libhttpserver-specific options are listed below (the canonical configure options are also supported):

  • --enable-same-directory-build — enable in-tree builds. Strongly discouraged. (default: no)
  • --enable-debug — enable debug data generation. (default: no)
  • --disable-doxygen-doc — don't generate any Doxygen documentation. Doxygen is automatically invoked when present on the system and disabled otherwise.
  • --enable-fastopen — enable use of TCP_FASTOPEN. (default: yes)
  • --enable-static — enable static linking. (default: yes)

Build-time feature flags (auto-detected, can be forced):

  • --with-gnutls / --without-gnutls — enable/disable TLS support. Sets the HAVE_GNUTLS macro.
  • --with-basic-auth / --without-basic-auth — enable/disable Basic auth. Sets HAVE_BAUTH.
  • --with-digest-auth / --without-digest-auth — enable/disable Digest auth. Sets HAVE_DAUTH.
  • --with-websocket / --without-websocket — enable/disable WebSocket support. Sets HAVE_WEBSOCKET. Requires libmicrohttpd built with WebSocket support.

See Feature availability for how each of these flags affects the runtime API.

Back to TOC

Building on Windows (MSYS2)

MSYS2 provides multiple shell environments with different purposes. Understanding which shell to use is important:

Shell Host triplet Runtime dependency Use case
MinGW64 x86_64-w64-mingw32 Native Windows Recommended for native Windows apps
MSYS x86_64-pc-msys msys-2.0.dll POSIX-style apps, build tools

Recommended: use the MinGW64 shell for building libhttpserver to produce native Windows binaries without additional runtime dependencies.

Step-by-step build instructions

  1. Install MSYS2.
  2. Open the MINGW64 shell (not the MSYS shell) from the Start Menu.
  3. Install dependencies:
pacman -S --needed mingw-w64-x86_64-{gcc,libtool,make,pkg-config,doxygen,gnutls,curl} autotools
  1. Build and install libmicrohttpd (>= 1.0.0).
  2. Build libhttpserver:
./bootstrap
mkdir build && cd build
../configure --disable-fastopen
make
make check  # run tests

Important: the --disable-fastopen flag is required on Windows as TCP_FASTOPEN is not supported there.

If you use the MSYS shell

Building from the MSYS shell also works, but the resulting binaries will depend on msys-2.0.dll. The configure script will emit a warning when building in this environment:

configure: WARNING: Building from MSYS environment. Binaries will depend on msys-2.0.dll.

Consider switching to the MinGW64 shell for native Windows binaries.

Library files on Windows

When building with GCC-based toolchains (MSYS2/MinGW, Cygwin), the following library files are generated:

File Purpose
libhttpserver.a Static library archive
libhttpserver.dll Shared library (DLL)
libhttpserver.dll.a Import library for linking against the DLL
libhttpserver.la Libtool archive (used by libtool during linking)

Note about .lib files: the .dll.a format is the import library format used by GCC toolchains. If you're looking for .lib files, those are the MSVC (Microsoft Visual C++) import library format and are only generated when building with the MSVC toolchain. The .dll.a file serves the same purpose as .lib but for GCC-based compilers.

Linking against libhttpserver:

Using pkg-config (recommended):

g++ myapp.cpp $(pkg-config --cflags --libs libhttpserver) -o myapp

Manual linking:

g++ myapp.cpp -I/mingw64/include -L/mingw64/lib -lhttpserver -lmicrohttpd -o myapp

Back to TOC

Getting started — Hello, world

The Tl;dr at the top of this README contains the entire program. Walking through it:

  • webserver ws{create_webserver(8080)}; — create_webserver is a fluent builder for the server configuration; webserver is constructed by direct initialisation from the builder. webserver is non-copyable and non-movable; pass it by reference once it exists. The constructor is explicit, so callers must direct-init rather than rely on implicit conversion.
  • ws.on_get("/hello", [](const http_request&) { ... }); — register a GET-only handler. The handler is a std::function<http_response(const http_request&)>. There is no subclass, no shared_ptr, no raw pointer. The seven HTTP-verb shortcuts are on_get, on_post, on_put, on_delete, on_patch, on_options, and on_head. For CONNECT and TRACE, use the route(http_method::CONNECT, ...) and route(http_method::TRACE, ...) forms covered under Routing.
  • return http_response::string("Hello, World!"); — http_response is a value type. Factories on http_response build common shapes; the fluent with_* mutators add headers, footers, cookies, and status. The response is returned by value into the dispatcher.
  • ws.start(true); — true means block this thread until the server is stopped. Pass false to start the listener and return immediately; later call stop_and_wait() from another thread.

To test the example, you can run the following from a terminal:

curl -XGET -v http://localhost:8080/hello

See examples/hello_world.cpp and examples/hello_with_get_arg.cpp for the complete sources.

Back to TOC

Class-form handlers

Lambdas suffice when each HTTP method is independent. When several methods on one path share state — a counter, a cache, a mutex — derive from http_resource and register the subclass once:

class counter : public httpserver::http_resource {
 public:
    httpserver::http_response render_get(const httpserver::http_request&) override {
        std::lock_guard lock{m_};
        return httpserver::http_response::string(std::to_string(n_));
    }
    httpserver::http_response render_post(const httpserver::http_request&) override {
        std::lock_guard lock{m_};
        ++n_;
        return httpserver::http_response::string(std::to_string(n_));
    }
 private:
    std::mutex m_;
    int n_ = 0;
};

// ...
ws.register_path("/count", std::make_unique<counter>());

The virtual hooks are render_get, render_post, render_put, render_delete, render_head, render_options, render_patch, render_connect, and render_trace — all lowercase, all returning http_response by value. The webserver takes ownership of the resource via std::unique_ptr (or a std::shared_ptr overload — see Routing).

See examples/shared_state.cpp for the canonical example.

Back to TOC

Structures and classes type definition

This is the cast of types you will work with. Each is detailed further on in its own section.

  • webserver — represents the daemon listening on a socket for HTTP traffic. Non-copyable, non-movable. See Create and work with a webserver.
    • create_webserver — fluent builder for the configuration that webserver's explicit constructor consumes. See the same section.
  • http_resource — base class for a logical collection of HTTP methods bound to a path. Override the snake_case render_* virtuals. See The resource object.
  • http_request — the request passed to handlers. Read-only, single-threaded per request. See Request.
  • http_response — the value-typed response. Seven factories cover every body shape; fluent with_* mutators add headers, footers, cookies, and status. See Response.
    • Factories: http_response::string, http_response::file, http_response::iovec, http_response::pipe, http_response::empty, http_response::deferred, http_response::unauthorized.
  • http_method — strongly-typed enum of HTTP verbs (GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, CONNECT, TRACE). Declared in http_method.hpp.
  • method_set — small bitset of http_method values, used by route() for atomic multi-method registration.
  • iovec_entry — element type for http_response::iovec scatter-gather responses. A { void* base, size_t length } pair where the base pointer is borrowed for the lifetime of the response.
  • websocket_handler — base class for handling WebSocket connections; derive and implement on_message. See WebSocket support.
    • websocket_session — represents an active WebSocket connection; methods to send text, binary, ping/pong, and close frames.
  • feature_unavailable — std::runtime_error subclass thrown when application code requests a feature that was compiled out (no TLS, no Basic auth, no Digest auth, no WebSocket). See Feature availability.

Back to TOC

Create and work with a webserver

Creating a webserver with a standard configuration is the one-liner shown in the Tl;dr:

webserver ws{create_webserver(8080)};

create_webserver is a fluent builder: every setter returns *this so calls chain. The webserver constructor is explicit: callers must direct-initialise (webserver ws{cw};) rather than rely on implicit conversion. The builder validates eagerly where the input domain is

Description taken from the repository README.

Ratings

–
0 ratings
5 0
4 0
3 0
2 0
1 0

Rate this app

Sign in to rate

Comments 0

Sign in to comment

No comments yet.

Related apps

#http · #server · #cpp