cpp-httplib

A C++11 single-file header-only cross platform HTTP/HTTPS library.
It’s extremely easy to set up. Just include the httplib.h file in your code!
Learn more in the official documentation (built with docs-gen).
This library uses ‘blocking’ socket I/O. If you are looking for a library with ‘non-blocking’ socket I/O, this is not the one that you want. Only HTTP/1.1 is supported — HTTP/2 and HTTP/3 are not implemented.
32-bit platforms are NOT supported. Use at your own risk. The library may compile on 32-bit targets, but no security review has been conducted for 32-bit environments. Integer truncation and other 32-bit-specific issues may exist. Security reports that only affect 32-bit platforms will be closed without action. The maintainer does not have access to 32-bit environments for testing or fixing issues. CI includes basic compile checks only, not functional or security testing.
Main Features
Simple examples
Server
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
// HTTP
httplib::Server svr;
// HTTPS
httplib::SSLServer svr("./cert.pem", "./key.pem");
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
res.set_content("Hello World!", "text/plain");
});
svr.listen("0.0.0.0", 8080);
Client
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
// HTTP
httplib::Client cli("http://yhirose.github.io");
// HTTPS
httplib::Client cli("https://yhirose.github.io");
if (auto res = cli.Get("/hi")) {
res->status;
res->body;
}
SSL/TLS Support
cpp-httplib supports multiple TLS backends through an abstraction layer:
| Backend |
Define |
Libraries |
Notes |
| OpenSSL |
CPPHTTPLIB_OPENSSL_SUPPORT |
libssl, libcrypto |
3.0 or later required |
| Mbed TLS |
CPPHTTPLIB_MBEDTLS_SUPPORT |
libmbedtls, libmbedx509, libmbedcrypto |
2.x, 3.x, and 4.x supported (auto-detected); 4.x renames libmbedcrypto to libtfpsacrypto |
| wolfSSL |
CPPHTTPLIB_WOLFSSL_SUPPORT |
libwolfssl |
5.x supported; must build with --enable-opensslall |
Mbed TLS threading: Mbed TLS must be built with MBEDTLS_THREADING_C, because SSLServer handles connections on several threads and Mbed TLS is not thread-safe without it. Its default configuration leaves this option off, while distribution packages such as Debian, Ubuntu and Homebrew turn it on. Building against Mbed TLS without it stops with an #error. If Mbed TLS is only ever used from one thread, define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED to build anyway.
wolfSSL limitation: get_ca_certs() and get_ca_names() only reflect CA certificates loaded via load_ca_cert_store() or set_ca_cert_store(). Certificates loaded through set_ca_cert_path() or system certificates (load_system_certs) are not enumerable.
A wolfSSL server that verifies client certificates does not resume TLS sessions: wolfSSL shares its session cache between contexts, so a resumed session could carry a certificate checked against another server’s client CA.
BoringSSL (best-effort): BoringSSL builds under CPPHTTPLIB_OPENSSL_SUPPORT and is exercised by CI against current upstream. Because BoringSSL does not guarantee API stability, support is best-effort — breakage may occasionally land. One known difference vs OpenSSL: BoringSSL’s public headers require C++14 or later, so consumers must compile accordingly.
Hostname verification is SAN-only on every backend (RFC 9525). A host is matched against the certificate’s subjectAltName entries, never its Common Name, so a certificate that names its host only in the CN is rejected. Reissue it with a subjectAltName.
// Use either OpenSSL, Mbed TLS, or wolfSSL
#define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT
#include "path/to/httplib.h"
// Server
httplib::SSLServer svr("./cert.pem", "./key.pem");
// Client
httplib::Client cli("https://localhost:1234"); // scheme + host
httplib::SSLClient cli("localhost"); // host (port 443)
httplib::SSLClient cli("localhost", 1234); // host, port
// Use your CA bundle
cli.set_ca_cert_path("./ca-bundle.crt");
// Disable cert verification
cli.enable_server_certificate_verification(false);
// Disable host verification
cli.enable_server_hostname_verification(false);
The CA certificates are loaded when the client makes its first connection. Changing set_ca_cert_path() or enable_system_ca() after that has no effect, so make the settings before the first request, or use a new client. set_ca_cert_store() and load_ca_cert_store() take effect at once. WebSocketClient works the same way. On Client and SSLClient, a setter that changes a TLS setting also closes a connection kept alive under the old one, so the next request connects again.
SSL Error Handling
When SSL operations fail, cpp-httplib provides detailed error information through ssl_error() and ssl_backend_error():
ssl_error() - Returns the TLS-level error as a backend-independent httplib::tls::ErrorCode value (e.g., Fatal, CertVerifyFailed), cast to int. A server certificate that the built-in verification rejects reports CertVerifyFailed, or HostnameMismatch when only its name does not match
ssl_backend_error() - Returns the backend-specific error code (e.g., ERR_get_error() for OpenSSL/wolfSSL, return value for Mbed TLS). With OpenSSL, a certificate verification failure reports the verify result (X509_V_ERR_*) here instead. On Windows, when CryptoAPI verifies the chain, a failure there reports the CryptoAPI error code here
A request that fails after the handshake with Error::Read or Error::Write also carries the TLS error behind it in both values, such as a TLS 1.3 “certificate required” alert from the server. Both values are reset for each request.
#define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT
#include "path/to/httplib.h"
httplib::Client cli("https://example.com");
auto res = cli.Get("/");
if (!res) {
// Check the error type
const auto err = res.error();
switch (err) {
case httplib::Error::SSLConnection:
std::cout << "SSL connection failed, SSL error: "
<< res.ssl_error() << std::endl;
break;
case httplib::Error::SSLLoadingCerts:
std::cout << "SSL cert loading failed, backend error: "
<< std::hex << res.ssl_backend_error() << std::endl;
break;
case httplib::Error::SSLServerVerification:
std::cout << "SSL verification failed, verify error: "
<< res.ssl_backend_error() << std::endl;
break;
case httplib::Error::SSLServerHostnameVerification:
std::cout << "SSL hostname verification failed, verify error: "
<< res.ssl_backend_error() << std::endl;
break;
default:
std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
}
}
Custom Certificate Verification
You can set a custom verification callback using tls::VerifyCallback:
httplib::Client cli("https://example.com");
cli.set_server_certificate_verifier(
[](const httplib::tls::VerifyContext &ctx) -> bool {
std::cout << "Subject CN: " << ctx.subject_cn() << std::endl;
std::cout << "Issuer: " << ctx.issuer_name() << std::endl;
std::cout << "Depth: " << ctx.depth << std::endl;
std::cout << "Pre-verified: " << ctx.preverify_ok << std::endl;
// Inspect SANs (Subject Alternative Names)
for (const auto &san : ctx.sans()) {
std::cout << "SAN: " << san.value << std::endl;
}
// Return false to reject
return ctx.preverify_ok;
});
Returning false, or throwing, rejects the certificate. The callback runs alongside the built-in verification, so to accept a certificate that verification rejects, such as a self-signed one, also call enable_server_certificate_verification(false); the callback is then the only check.
Mutual TLS (mTLS)
Regular TLS only verifies the server certificate. With mTLS, the client also presents a certificate that the server verifies.
// Server: pass a CA to verify client certificates against
httplib::SSLServer svr("./cert.pem", "./key.pem", "./client-ca-cert.pem");
// Client: present a certificate
httplib::SSLClient cli("api.example.com", 443,
"./client-cert.pem", "./client-key.pem");
Both SSLServer and SSLClient also accept an in-memory PemMemory struct instead of file paths — handy when certs come from an environment variable or a secrets manager:
httplib::SSLServer::PemMemory server_pem{};
server_pem.cert_pem = server_cert.data();
server_pem.cert_pem_len = server_cert.size();
server_pem.key_pem = server_key.data();
server_pem.key_pem_len = server_key.size();
server_pem.client_ca_pem = client_ca.data();
server_pem.client_ca_pem_len = client_ca.size();
httplib::SSLServer svr(server_pem);
httplib::SSLClient::PemMemory client_pem{};
client_pem.cert_pem = client_cert.data();
client_pem.cert_pem_len = client_cert.size();
client_pem.key_pem = client_key.data();
client_pem.key_pem_len = client_key.size();
httplib::SSLClient cli("api.example.com", 443, client_pem);
A length of 0 means the field is a NUL-terminated string.
httplib::ws::WebSocketClient has the same PemMemory constructor for wss:// connections. See README-websocket.md for details.
Peer Certificate Inspection
On the server side, you can inspect the client’s peer certificate from a request handler:
httplib::SSLServer svr("./cert.pem", "./key.pem",
"./client-ca-cert.pem");
svr.Get("/", [](const httplib::Request &req, httplib::Response &res) {
auto cert = req.peer_cert();
if (cert) {
std::cout << "Client CN: " << cert.subject_cn() << std::endl;
std::cout << "Serial: " << cert.serial() << std::endl;
}
auto sni = req.sni();
std::cout << "SNI: " << sni << std::endl;
});
cpp-httplib automatically integrates with the OS certificate store on macOS and Windows. This works with all TLS backends.
| Platform |
Behavior |
Disable (compile time) |
| macOS |
Loads system certs from Keychain, honouring their Trust Settings: a certificate set to “Never Trust”, or trusted only for another policy such as S/MIME, is not loaded (link CoreFoundation and Security with -framework). Requires Apple Clang; GCC is not supported for this feature. |
CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES |
| Windows |
Verifies the certificate chain with CryptoAPI (CertGetCertificateChain / CertVerifyCertificateChainPolicy) instead of the TLS backend. Revocation checking is best-effort: a revoked server certificate is rejected, while one whose revocation status cannot be determined is accepted. Windows fetches missing roots and intermediates on demand. With a custom CA, the TLS backend verifies the chain instead; with set_server_certificate_verifier(), both do. |
CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE |
On Windows, the CryptoAPI check can also be turned off at runtime. The TLS backend then verifies the chain instead, as on other platforms:
cli.enable_windows_certificate_verification(false);
WebSocketClient verifies the same way and has the same enable_windows_certificate_verification().
When using SSL, it seems impossible to avoid SIGPIPE in all cases, since on some operating systems, SIGPIPE can only be suppressed on a per-message basis, but there is no way to make the OpenSSL library do so for its internal communications. If your program needs to avoid being terminated on SIGPIPE, the only fully general way might be to set up a signal handler for SIGPIPE to handle or ignore it yourself.
On systems other than Windows, the Server constructor does this already: it calls signal(SIGPIPE, SIG_IGN), which affects the whole process. A program that only uses clients has to do it itself.
Server
#include <httplib.h>
int main(void)
{
using namespace httplib;
Server svr;
svr.Get("/hi", [](const Request& req, Response& res) {
res.set_content("Hello World!", "text/plain");
});
// Match the request path against a regular expression
// and extract its captures
svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
auto numbers = req.matches[1];
res.set_content(numbers, "text/plain");
});
// Capture the second segment of the request path as "id" path param
svr.Get("/users/:id", [&](const Request& req, Response& res) {
auto user_id = req.path_params.at("id");
res.set_content(user_id, "text/plain");
});
// Extract values from HTTP headers and URL query params
svr.Get("/body-header-param", [](const Request& req, Response& res) {
if (req.has_header("Content-Length")) {
auto val = req.get_header_value("Content-Length");
}
if (req.has_param("key")) {
auto val = req.get_param_value("key");
}
// Get all values for a given key (e.g., ?tag=a&tag=b)
auto values = req.get_param_values("tag");
res.set_content(req.body, "text/plain");
});
// If the handler takes time to finish, you can also poll the connection state
svr.Get("/task", [&](const Request& req, Response& res) {
const char * result = nullptr;
process.run(); // for example, starting an external process
while (result == nullptr) {
sleep(1);
if (req.is_connection_closed()) {
process.kill(); // kill the process
return;
}
result = process.stdout(); // != nullptr if the process finishes
}
res.set_content(result, "text/plain");
});
svr.Get("/stop", [&](const Request& req, Response& res) {
svr.stop();
});
svr.listen("localhost", 1234);
}
Post, Put, Patch, Delete and Options methods are also supported.
Custom HTTP methods
Methods outside the built-in set are rejected with 400 Bad Request unless a handler is registered for them with CustomRoute. This covers the WebDAV methods of RFC 4918, SUBSCRIBE and friends from UPnP, and any other extension method.
svr.CustomRoute("PROPFIND", "/dav/:id", [](const Request& req, Response& res) {
// The request body is available as usual
auto id = req.path_params.at("id");
res.status = StatusCode::MultiStatus_207;
res.set_content(build_multistatus(req.body), "application/xml");
});
// A content reader overload is available too
svr.CustomRoute("REPORT", "/dav/.*",
[](const Request& req, Response& res,
const ContentReader& content_reader) {
content_reader([&](const char* data, size_t data_length) {
// ...
return true;
});
});
Patterns work exactly as they do for Get and the other methods, so regular expressions and path parameters are both available.
Note the following:
- The method name must be a valid HTTP method token (RFC 9110) and must be registered before
listen() is called.
GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH and PRI cannot be registered this way. Use Get (which also serves HEAD), Post, Put, Delete, Options or Patch instead. There are no handlers for CONNECT, TRACE and PRI; such requests get 400 Bad Request.
- A rejected registration makes
is_valid() return false, and listen() then fails rather than starting a server with a route that would never fire.
- Static file serving remains
GET/HEAD only, and WebSocket upgrades GET only.
Allow and the WebDAV DAV: header are not generated automatically. Register an Options handler if clients need them.
The request line and the Host header are read strictly, as RFC 9112 asks: a single space between the three parts of the request line, HTTP/1.0 or HTTP/1.1 as the version, no fragment (#...) in the target, and exactly one valid Host header (an HTTP/1.0 request may have none). Anything else gets 400 Bad Request.
Bind a socket to multiple interfaces and any available port
int port = svr.bind_to_any_port("0.0.0.0");
svr.listen_after_bind();
Port sharing and exclusive binding
By default, the server socket enables address/port reuse: SO_REUSEPORT where it is available (Linux, macOS), and SO_REUSEADDR otherwise (Windows). A restarted server can bind again immediately, but binding to a port that another server is already listening on also succeeds, and connections are distributed between them.
If you want listen() to fail when the port is already in use, replace the default socket options with set_socket_options:
svr.set_socket_options([](socket_t sock) {
#ifdef _WIN32
httplib::set_socket_opt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1);
#else
httplib::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
#endif
});
Setting only SO_REUSEADDR is not enough on Windows. There, SO_REUSEADDR allows two sockets that both set it to bind to the same port, so use SO_EXCLUSIVEADDRUSE instead.
Static File Server
// Mount / to ./www directory
auto ret = svr.set_mount_point("/", "./www");
if (!ret) {
// The specified base directory doesn't exist...
}
// Mount /public to ./www directory
ret = svr.set_mount_point("/public", "./www");
// Mount /public to ./www1 and ./www2 directories
ret = svr.set_mount_point("/public", "./www1"); // 1st order to search
ret = svr.set_mount_point("/public", "./www2"); // 2nd order to search
// Remove mount /
ret = svr.remove_mount_point("/");
// Remove mount /public
ret = svr.remove_mount_point("/public");
A mount point serves a path only when it has no ., .. or empty segment other than a trailing /, no segment ending in . or a space and, on Windows, no : (it names an NTFS stream), so a check on req.path in set_pre_routing_handler() sees the path of the file that is served. A path ending in /, and the mount point itself such as /public, serve the index.html in that directory. The file system can still give a file other names: another case on a case-insensitive file system, such as the default ones on macOS and Windows, and on Windows an 8.3 short name such as PRIVAT~1. Compare paths without regard to case on such a file system, and on Windows keep files that need a guard out of mounted directories.
// User defined file extension and MIME type mappings
svr.set_file_extension_and_mimetype_mapping("cc", "text/x-c");
svr.set_file_extension_and_mimetype_mapping("cpp", "text/x-c");
svr.set_file_extension_and_mimetype_mapping("hh", "text/x-h");
Extensions match regardless of case, so photo.JPG is served as image/jpeg. The extension of a user mapping can be given in any case, with or without a leading ..
The following are built-in mappings:
| Extension |
MIME Type |
Extension |
MIME Type |
| css |
text/css |
mpga |
audio/mpeg |
| csv |
text/csv |
weba |
audio/webm |
| txt |
text/plain |
wav |
audio/wave |
| vtt |
text/vtt |
otf |
font/otf |
| html, htm |
text/html |
ttf |
font/ttf |
| apng |
image/apng |
woff |
font/woff |
| avif |
image/avif |
woff2 |
font/woff2 |
| bmp |
image/bmp |
7z |
application/x-7z-compressed |
| gif |
image/gif |
atom |
application/atom+xml |
| png |
image/png |
pdf |
application/pdf |
| svg |
image/svg+xml |
mjs, js |
text/javascript |
| webp |
image/webp |
json |
application/json |
| ico |
image/x-icon |
rss |
application/rss+xml |
| tif |
image/tiff |
tar |
application/x-tar |
| tiff |
image/tiff |
xhtml, xht |
application/xhtml+xml |
| jpeg, jpg |
image/jpeg |
xslt |
application/xslt+xml |
| mp4 |
video/mp4 |
xml |
application/xml |
| mpeg |
video/mpeg |
gz |
application/gzip |
| webm |
video/webm |
zip |
application/zip |
| mp3 |
audio/mp3 |
wasm |
application/wasm |
These static file server methods are not thread-safe.
On POSIX systems, the static file server rejects requests that resolve (via symlinks) to a path outside the mounted base directory. Ensure that the served directory has appropriate permissions, as managing access to the served directory is the application developer’s responsibility.
File request handler
// The handler is called right before the response is sent to a client
svr.set_file_request_handler([](const Request &req, Response &res) {
...
});
It is not called for HEAD requests or 304 Not Modified responses, so do not use it for access control; use set_pre_routing_handler().
Logging
cpp-httplib provides separate logging capabilities for access logs and error logs, similar to web servers like Nginx and Apache.
Access Logging
Access loggers capture each request and the response written for it, including the error responses the library writes itself, such as 400, 404, 413 or 500:
svr.set_logger([](const httplib::Request& req, const httplib::Response& res) {
std::cout << req.method << " " << req.path << " -> " << res.status << std::endl;
});
req.path is percent-decoded and may contain control characters such as CR/LF. Escape request data before writing it to a log file (see docker/main.cc for an example).
Pre-compression Logging
You can also set a pre-compression logger to capture request/response data before compression is applied:
svr.set_pre_compression_logger([](const httplib::Request& req, const httplib::Response& res) {
// Log before compression - res.body contains uncompressed content
// Content-Encoding header is not yet set
your_pre_compression_logger(req, res);
});
The pre-compression logger is only called when the server compresses res.body or a static file. It is not called for a response without compression, nor for a chunked content provider, whose body is compressed as it is written; for those, only the access logger is called.
For a static file response (see Static file compression), res.body is empty when the logger runs. The bytes are still on disk at that point, not in memory.
Error Logging
Error loggers capture failed requests and connection issues. Unlike access loggers, error loggers only receive the Error and Request information, as errors typically occur before a meaningful Response can be generated.
svr.set_error_logger([](const httplib::Error& err, const httplib::Request* req) {
std::cerr << httplib::to_string(err) << " while processing request";
if (req) {
std::cerr << ", client: " << req->get_header_value("X-Forwarded-For")
<< ", request: '" << req->method << " " << req->path << " " << req->version << "'"
<< ", host: " << req->get_header_value("Host");
}
std::cerr << std::endl;
});
Error handler
svr.set_error_handler([](const auto& req, auto& res) {
auto fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
char buf[BUFSIZ];
snprintf(buf, sizeof(buf), fmt, res.status);
res.set_content(buf, "text/html");
});
Exception handler
The exception handler gets called if a user routing handler throws an error. This covers the pre-routing handler, the file request handler, the pre-request handler, route handlers, content readers and, on a WebSocket upgrade, the sub-protocol selector. The response is a 500 unless the exception handler sets another status. An exception from the post-routing handler, the error handler, the Expect: 100-continue handler, a content provider, a logger or a WebSocket handler does not reach it: the connection is dropped, and the error logger receives Error::UserCallbackException.
svr.set_exception_handler([](const auto& req, auto& res, std::exception_ptr ep) {
auto fmt = "<h1>Error 500</h1><p>%s</p>";
char buf[BUFSIZ];
try {
std::rethrow_exception(ep);
} catch (std::exception &e) {
snprintf(buf, sizeof(buf), fmt, e.what());
} catch (...) { // See the following NOTE
snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
}
res.set_content(buf, "text/html");
res.status = StatusCode::InternalServerError_500;
});
If you don’t provide the catch (...) block for a rethrown exception pointer, an exception that is not a std::exception escapes the handler. The server keeps running, but that connection is dropped without a response, and the error logger receives Error::UserCallbackException.
Pre routing handler
svr.set_pre_routing_handler([](const auto& req, auto& res) {
if (req.path == "/hello") {
res.set_content("world", "text/html");
return Server::HandlerResponse::Handled;
}
return Server::HandlerResponse::Unhandled;
});
Post routing handler
svr.set_post_routing_handler([](const auto& req, auto& res) {
res.set_header("ADDITIONAL_HEADER", "value");
});
Pre request handler
The pre-request handler runs after the route has been matched (so req.matched_route and req.path_params are available) but before the request body is read. This means you can reject a request — for example on a failed authentication or authorization check — without forcing the server to buffer a potentially large body.
svr.set_pre_request_handler([](const auto& req, auto& res) {
if (req.matched_route == "/user/:user") {
auto user = req.path_params.at("user");
if (user != "john") {
res.status = StatusCode::Forbidden_403;
res.set_content("error", "text/html");
return Server::HandlerResponse::Handled;
}
}
return Server::HandlerResponse::Unhandled;
});
Because the body has not been read yet, req.body and form fields parsed from the body are not available in the pre-request handler. Inspect headers, the path, query parameters, or req.matched_route instead.
Accept handler
The accept handler runs for each accepted connection before anything is read from it, and before the TLS handshake on SSLServer. Return false to close the connection.
svr.set_accept_handler([](socket_t sock) {
sockaddr_storage addr;
socklen_t len = sizeof(addr);
if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
return false;
}
return is_allowed(addr); // Your own check
});
The handler runs on the thread that accepts connections, so a slow handler delays every new connection. With set_keep_alive_parking(true), that thread also hands out the next requests on kept-alive connections, so those wait too. The server owns sock and closes it after a refusal, so the handler must not close it. If the handler throws, the connection is closed and the error logger receives Error::UserCallbackException.
Handler execution order
set_start_handler runs once when the server starts, and set_accept_handler once for each connection, before any request on it. For each request, handlers run in the following order:
Request received
│
├─ expect_100_continue_handler (when the request has "Expect: 100-continue")
│ └─ returns a status other than 100 → go straight to post_routing_handler
│
├─ pre_routing_handler route not matched yet, body not read
│ └─ returns Handled → go straight to post_routing_handler
│
├─ file_request_handler when a static file is served (GET only)
│ └─ a mount point answered → go straight to post_routing_handler
│
├─ route matching → req.matched_route is set
│
├─ pre_request_handler route matched, body NOT read yet
│ └─ returns Handled → go straight to post_routing_handler
│
├─ route handler Get/Post/...; the request body is read first
│
└─ post_routing_handler just before the response is written
On a thrown exception → exception_handler
On an error status (4xx/5xx) → error_handler
Use pre_routing_handler to reject a request as early as possible, before the route is known. Use pre_request_handler for route-specific checks, since req.matched_route is available and the body has not been read yet. A request that a mount point answers never reaches route matching or pre_request_handler, so reject such a request in pre_routing_handler.
For a request with Expect: 100-continue, the 100 Continue response is not sent until the body is about to be read. A request rejected before that point (by pre_routing_handler, pre_request_handler, or because no route matched) gets its final response without 100 Continue, so the client never sends the body.
A WebSocket upgrade request that matches a route registered with svr.WebSocket() takes a shorter path: pre_routing_handler, then route matching (req.matched_route is set), then pre_request_handler, then the WebSocket handler. If either hook returns Handled, its response is sent as a regular HTTP response and the connection is not upgraded. Once the connection is upgraded, post_routing_handler does not run.
Response user data
res.user_data is a type-safe key-value store that lets pre-routing or pre-request handlers pass arbitrary data to route handlers.
struct AuthContext {
std::string user_id;
std::string role;
};
svr.set_pre_routing_handler([](const auto& req, auto& res) {
auto token = req.get_header_value("Authorization");
res.user_data.set("auth", AuthContext{decode_token(token)});
return Server::HandlerResponse::Unhandled;
});
svr.Get("/me", [](const Request& /*req*/, Response& res) {
auto* ctx = res.user_data.get<AuthContext>("auth");
if (!ctx) {
res.status = StatusCode::Unauthorized_401;
return;
}
res.set_content("Hello " + ctx->user_id, "text/plain");
});
svr.Post("/form", [&](const auto& req, auto& res) {
// URL query parameters and form-encoded data are accessible via req.params
std::string username = req.get_param_value("username");
std::string password = req.get_param_value("password");
// Handle multiple values with same name
auto interests = req.get_param_values("interests");
// Check existence
if (req.has_param("newsletter")) {
// Handle newsletter subscription
}
});
‘multipart/form-data’ POST data
svr.Post("/multipart", [&](const Request& req, Response& res) {
// Access text fields (from form inputs without files)
std::string username = req.form.get_field("username");
std::string bio = req.form.get_field("bio");
// Access uploaded files
if (req.form.has_file("avatar")) {
const auto& file = req.form.get_file("avatar");
std::cout << "Uploaded file: " << file.filename
<< " (" << file.content_type << ") - "
<< file.content.size() << " bytes" << std::endl;
// Access additional headers if needed
for (const auto& header : file.headers) {
std::cout << "Header: " << header.first << " = " << header.second << std::endl;
}
// IMPORTANT: file.filename is an untrusted value from the client.
// Always sanitize to prevent path traversal attacks.
auto safe_name = httplib::sanitize_filename(file.filename);
if (safe_name.empty()) {
res.status = StatusCode::BadRequest_400;
res.set_content("Invalid filename", "text/plain");
return;
}
// Save to disk
std::ofstream ofs(upload_dir + "/" + safe_name, std::ios::binary);
ofs << file.content;
}
// Handle multiple values with same name
auto tags = req.form.get_fields("tags"); // e.g., multiple checkboxes
for (const auto& tag : tags) {
std::cout << "Tag: " << tag << std::endl;
}
auto documents = req.form.get_files("documents"); // multiple file upload
for (const auto& doc : documents) {
std::cout << "Document: " << doc.filename
<< " (" << doc.content.size() << " bytes)" << std::endl;
}
// Check existence before accessing
if (req.form.has_field("newsletter")) {
std::cout << "Newsletter subscription: " << req.form.get_field("newsletter") << std::endl;
}
// Get counts for validation
if (req.form.get_field_count("tags") > 5) {
res.status = StatusCode::BadRequest_400;
res.set_content("Too many tags", "text/plain");
return;
}
// Summary
std::cout << "Received " << req.form.fields.size() << " text fields and "
<< req.form.files.size() << " files" << std::endl;
res.set_content("Upload successful", "text/plain");
});
Filename Sanitization
file.filename in multipart uploads is an untrusted value from the client. Always sanitize before using it in file paths:
auto safe = httplib::sanitize_filename(file.filename);
This function keeps only the part after the last / or \ (or, on Windows, :, which starts a drive prefix such as C: or an NTFS stream name), removes null bytes, and trims leading and trailing spaces and tabs. It returns an empty string if what is left is empty, . or ...
name and filename are read as quoted-strings (RFC 9110 §5.6.4), where \" and \\ stand for " and \. Browsers send a backslash as it is, so from a browser, a value with \\ in it arrives with a single \, and one that ends in \ is not read correctly.
Receive content with a content receiver
svr.Post("/content_receiver",
[&](const Request &req, Response &res, const ContentReader &content_reader) {
if (req.is_multipart_form_data()) {
// NOTE: `content_reader` is blocking until every form data field is read
// This approach allows streaming processing of large files
std::vector<FormData> items;
content_reader(
[&](const FormData &item) {
items.push_back(item);
return true;
},
[&](const char *data, size_t data_length) {
items.back().content.append(data, data_length);
return true;
});
// Process the received items
for (const auto& item : items) {
if (item.filename.empty()) {
// Text field
std::cout << "Field: " << item.name << " = " << item.content << std::endl;
} else {
// File
std::cout << "File: " << item.name << " (" << item.filename << ") - "
<< item.content.size() << " bytes" << std::endl;
}
}
} else {
std::string body;
content_reader([&](const char *data, size_t data_length) {
body.append(data, data_length);
return true;
});
}
});
content_reader reads the body once per request; a second call returns false.
When a callback returns false, reading stops, content_reader returns false,
and res.status is set to 400 unless the handler sets another status. The
rest of the body is left unread, so the connection is closed after the response.
CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT (default 1024, 0 for no limit)
caps the number of form-data parts only on the buffered path, where every part
is accumulated into req.form. The content receiver keeps nothing, so the cap
does not apply here. If your handler needs an upper bound on the number of
parts, count them yourself and return false from the callback to stop the
parser.
Send content with the content provider
const size_t DATA_CHUNK_SIZE = 4;
svr.Get("/stream", [&](const Request &req, Response &res) {
auto data = new std::string("abcdefg");
res.set_content_provider(
data->size(), // Content length
"text/plain", // Content type
[&, data](size_t offset, size_t length, DataSink &sink) {
const auto &d = *data;
sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
return true; // return 'false' if you want to cancel the process.
},
[data](bool success) { delete data; });
});
Write at most length bytes per call. Anything past it is not sent, and the response fails. The response also fails if a call returns true without writing anything, or if sink.done() is called before the whole content length is written.
Without content length:
svr.Get("/stream", [&](const Request &req, Response &res) {
res.set_content_provider(
"text/plain", // Content type
[&](size_t offset, DataSink &sink) {
if (/* there is still data */) {
std::vector<char> data;
// prepare data...
sink.write(data.data(), data.size());
} else {
sink.done(); // No more data
}
return true; // return 'false' if you want to cancel the process.
});
});
Such a body ends where the connection does, so the server sends Connection: close and closes the connection after the response. Use set_chunked_content_provider() to keep the connection open.
Chunked transfer encoding
svr.Get("/chunked", [&](const Request& req, Response& res) {
res.set_chunked_content_provider(
"text/plain",
[](size_t offset, DataSink &sink) {
sink.write("123", 3);
sink.write("345", 3);
sink.write("789", 3);
sink.done(); // No more data
return true; // return 'false' if you want to cancel the process.
}
);
});
With trailer:
svr.Get("/chunked", [&](const Request& req, Response& res) {
res.set_header("Trailer", "Dummy1, Dummy2");
res.set_chunked_content_provider(
"text/plain",
[](size_t offset, DataSink &sink) {
sink.write("123", 3);
sink.write("345", 3);
sink.write("789", 3);
sink.done_with_trailer({
{"Dummy1", "DummyVal1"},
{"Dummy2", "DummyVal2"}
});
return true;
}
);
});
Send file content
svr.Get("/content", [&](const Request &req, Response &res) {
res.set_file_content("./path/to/content.html");
});
svr.Get("/content", [&](const Request &req, Response &res) {
res.set_file_content("./path/to/content", "text/html");
});
‘Expect: 100-continue’ handler
By default, the server accepts an Expect: 100-continue header and sends a 100 Continue response when it starts reading the request body. If the request is answered without reading the body, 100 Continue is not sent and the connection is closed after the response.
The handler runs before pre_routing_handler. Returning 100 lets the request proceed; returning any other status sends that status as the final response and closes the connection.
// Send a '417 Expectation Failed' response.
svr.set_expect_100_continue_handler([](const Request &req, Response &res) {
return StatusCode::ExpectationFailed_417;
});
// Send a final status without reading the message body.
svr.set_expect_100_continue_handler([](const Request &req, Response &res) {
return res.status = StatusCode::Unauthorized_401;
});
Keep-Alive connection
svr.set_keep_alive_max_count(2); // Default is 100, 0 for no limit
svr.set_keep_alive_timeout(10); // Default is 5
Keep-alive parking
Keep-alive parking is experimental. Its behavior may change in a future release.
svr.set_keep_alive_parking(true); // Call it before listen()
Defining CPPHTTPLIB_KEEPALIVE_PARKING as true turns it on for every Server from the start. If the event loop cannot be set up, the server serves as it does without it.
By default, a kept-alive connection holds a worker thread while it waits for its next request, so connections beyond the thread count wait for one to be closed. With keep-alive parking, a connection waiting for its next request is handed to an event loop instead, and goes back to a worker when the request arrives. An idle connection then costs a socket and a few kilobytes instead of a thread, and connections that outnumber the threads take turns.
With it:
- Consecutive requests on a connection may run on different threads.
- When the max queued requests limit is reached, only a connection that has not been served yet (or, with
SSLServer, has not finished its TLS handshake) is closed. An established one waits for room.
- Handing the connection over to a worker adds roughly 10-20 µs to each request. It only shows when the client is as near as loopback and the handlers are very light: in our measurements, 2 connections on 2 threads served about a third fewer requests per second over loopback, but only a few percent fewer with a 250 µs round trip.
- A handler, a content provider and a WebSocket still hold their thread while they run.
- A subclass that overrides the private
process_and_close_socket() is bypassed.
SSLServer runs the TLS handshake on a worker when the client starts it. Until then the connection waits in the event loop and is closed at the keep-alive timeout, not the read timeout, and ssl_last_error() is not set for it.
Client address behind a reverse proxy
svr.set_trusted_proxies({"10.0.0.2"});
A request that comes straight from one of these addresses gets req.remote_addr from X-Forwarded-For: the rightmost address in it that is not a trusted proxy. A request from anywhere else keeps the address of its connection, whatever X-Forwarded-For says. Addresses match as IP addresses, so an IPv4 peer that a server listening on both IPv4 and IPv6 sees as ::ffff:10.0.0.2 matches 10.0.0.2. Host names and CIDR ranges are not supported.
Timeout
svr.set_read_timeout(5, 0); // 5 seconds
svr.set_write_timeout(5, 0); // 5 seconds
svr.set_idle_interval(0, 100000); // 100 milliseconds
// std::chrono is also supported
svr.set_read_timeout(std::chrono::seconds(5));
svr.set_keep_alive_timeout(std::chrono::seconds(10));
The read timeout bounds the request line and headers as a whole, and each read of a request body. An error response closes the connection. Any other response to a request whose body was left unread, such as a redirect from a pre-routing handler, keeps the connection only when the rest of the body is at most CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH (256KB, 0 for no limit) and arrives within the read timeout, since the server has to read past it first.
Set maximum payload length for reading a request body
svr.set_payload_max_length(1024 * 1024 * 512); // 512MB
The default is CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100MB), and 0 means no limit. A request with a larger body gets 413 Payload Too Large.
When the request body content type is application/x-www-form-urlencoded, the body must not exceed CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH (8192 bytes by default, 0 for no limit). A larger one gets 413 Payload Too Large.
Server-Sent Events
Please see Server example and Client example.
Default thread pool support
ThreadPool is used as the default task queue, with dynamic scaling support. By default, it maintains a base thread count of 8 or std::thread::hardware_concurrency() - 1 (whichever is greater), and can scale up to 4x that count under load. You can change these with CPPHTTPLIB_THREAD_POOL_COUNT and CPPHTTPLIB_THREAD_POOL_MAX_COUNT.
When a new task arrives and the queued tasks outnumber the idle threads, a temporary thread is spawned (up to the maximum). A dynamic thread exits automatically once it has waited for the idle timeout without receiving a task. The idle timeout defaults to 3 seconds, configurable via CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT.
A connection holds its thread while it is served: between requests up to the keep-alive timeout (unless keep-alive parking is on), through a request body sent slowly but within the read timeout, and for the whole life of a WebSocket. Enough of them leave no thread for anyone else, so in front of untrusted clients, put a reverse proxy that limits connections per client, and reject unwanted WebSocket upgrades in the pre-request handler.
If you want to set the thread counts at runtime:
svr.new_task_queue = [] { return new ThreadPool(/*base_threads=*/8, /*max_threads=*/64); };
Max queued requests
You can also provide an optional parameter to limit the maximum number
of pending requests, i.e. requests accept()ed by the listener but
still waiting to be serviced by worker threads.
svr.new_task_queue = [] { return new ThreadPool(/*base_threads=*/12, /*max_threads=*/0, /*max_queued_requests=*/18); };
Default limit is 0 (unlimited). Once the limit is reached, the listener
will shutdown the client connection.
Idle timeout for dynamic threads
The idle timeout for dynamic threads can also be set at runtime via the
fourth parameter (in seconds):
svr.new_task_queue = [] { return new ThreadPool(/*base_threads=*/8, /*max_threads=*/64, /*max_queued_requests=*/0, /*idle_timeout_sec=*/10); };
Override the default thread pool with yours
You can supply your own thread pool implementation according to your need.
class YourThreadPoolTaskQueue : public TaskQueue {
public:
YourThreadPoolTaskQueue(size_t n) {
pool_.start_with_thread_count(n);
}
virtual bool enqueue(std::function<void()> fn) override {
/* Return true if the task was actually enqueued, or false
* if the caller must drop the corresponding connection. */
return pool_.enqueue(fn);
}
virtual void shutdown() override {
pool_.shutdown_gracefully();
}
private:
YourThreadPool pool_;
};
svr.new_task_queue = [] {
return new YourThreadPoolTaskQueue(12);
};
Client
#include <httplib.h>
#include <iostream>
int main(void)
{
httplib::Client cli("localhost", 1234);
if (auto res = cli.Get("/hi")) {
if (res->status == httplib::StatusCode::OK_200) {
std::cout << res->body << std::endl;
}
} else {
auto err = res.error();
std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
}
}
Constructor with scheme-host-port string is now supported!
httplib::Client cli("localhost");
httplib::Client cli("localhost:8080");
httplib::Client cli("http://localhost");
httplib::Client cli("http://localhost:8080");
httplib::Client cli("https://localhost");
httplib::SSLClient cli("localhost");
Error code
Here is the list of errors from Result::error().
enum class Error {
Success = 0,
Unknown,
Connection,
BindIPAddress,
Read,
Write,
ExceedRedirectCount,
Canceled,
SSLConnection,
SSLLoadingCerts,
SSLServerVerification,
SSLServerHostnameVerification,
UnsupportedMultipartBoundaryChars,
Compression,
ConnectionTimeout,
ProxyConnection,
ConnectionClosed,
Timeout,
ResourceExhaustion,
TooManyFormDataFiles,
ExceedMaxPayloadSize,
ExceedUriMaxLength,
ExceedMaxSocketDescriptorCount,
InvalidRequestLine,
InvalidHTTPMethod,
InvalidHTTPVersion,
InvalidHeaders,
MultipartParsing,
OpenFile,
Listen,
GetSockName,
UnsupportedAddressFamily,
HTTPParsing,
InvalidRangeHeader,
UnsupportedContentEncoding,
WebSocketHandshake,
UserCallbackException,
};
Client Logging
Access Logging
cli.set_logger([](const httplib::Request& req, const httplib::Response& res) {
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_time).count();
std::cout << "✓ " << req.method << " " << req.path
<< " -> " << res.status << " (" << res.body.size() << " bytes, "
<< duration << "ms)" << std::endl;
});
Error Logging
cli.set_error_logger([](const httplib::Error& err, const httplib::Request* req) {
std::cerr << "✗ ";
if (req) {
std::cerr << req->method << " " << req->path << " ";
}
std::cerr << "failed: " << httplib::to_string(err);
// Add specific guidance based on error type
switch (err) {
case httplib::Error::Connection:
std::cerr << " (verify server is running and reachable)";
break;
case httplib::Error::SSLConnection:
std::cerr << " (check SSL certificate and TLS configuration)";
break;
case httplib::Error::ConnectionTimeout:
std::cerr << " (increase timeout or check network latency)";
break;
case httplib::Error::Read:
std::cerr << " (server may have closed connection prematurely)";
break;
default:
break;
}
std::cerr << std::endl;
});
Each failed request is reported once, with the request you made, also when it failed on a redirect or was a stream that failed to open (open_stream(), stream::Get()).
httplib::Headers headers = {
{ "Hello", "World!" }
};
auto res = cli.Get("/hi", headers);
or
auto res = cli.Get("/hi", httplib::Headers{{"Hello", "World!"}});
or
cli.set_default_headers({
{ "Hello", "World!" }
});
auto res = cli.Get("/hi");
A Content-Length among these headers is sent in place of the one the library would send, so it has to match the body as written. One passed with the request is dropped when the library compresses the body or sends it chunked. A Transfer-Encoding is sent in addition to the library’s own framing, so leave it out. Leave both out when passing on the headers of another message, as a proxy does.
POST
res = cli.Post("/post", "text", "text/plain");
res = cli.Post("/person", "name=john1¬e=coder", "application/x-www-form-urlencoded");
POST with parameters
httplib::Params params;
params.emplace("name", "john");
params.emplace("note", "coder");
auto res = cli.Post("/post", params);
or
httplib::Params params{
{ "name", "john" },
{ "note", "coder" }
};
auto res = cli.Post("/post", params);
POST with Multipart Form Data
httplib::UploadFormDataItems items = {
{ "text1", "text default", "", "" },
{ "text2", "aωb", "", "" },
{ "file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain" },
{ "file2", "{\n \"world\", true\n}\n", "world.json", "application/json" },
{ "file3", "", "", "application/octet-stream" },
};
auto res = cli.Post("/multipart", items);
To upload files from disk without loading them entirely into memory, use make_file_provider. The file is sent with chunked transfer encoding.
httplib::FormDataProviderItems providers = {
httplib::make_file_provider("file1", "/path/to/large.bin", "large.bin", "application/octet-stream"),
httplib::make_file_provider("avatar", "/path/to/photo.jpg", "photo.jpg", "image/jpeg"),
};
auto res = cli.Post("/upload", {}, {}, providers);
POST with a file body
To POST a file as a raw binary body with Content-Length, use make_file_body.
auto [size, provider] = httplib::make_file_body("/path/to/data.bin");
auto res = cli.Post("/upload", size, provider, "application/octet-stream");
PUT
res = cli.Put("/resource/foo", "text", "text/plain");
PATCH
res = cli.Patch("/resource/foo", "text", "text/plain");
DELETE
res = cli.Delete("/resource/foo");
OPTIONS
res = cli.Options("*");
res = cli.Options("/resource/foo");
Timeout
cli.set_connection_timeout(0, 300000); // 300 milliseconds
cli.set_read_timeout(5, 0); // 5 seconds
cli.set_write_timeout(5, 0); // 5 seconds
// A deadline for the whole request (see below)
cli.set_max_timeout(5000); // 5 seconds
// std::chrono is also supported
cli.set_connection_timeout(std::chrono::milliseconds(300));
cli.set_read_timeout(std::chrono::seconds(5));
cli.set_write_timeout(std::chrono::seconds(5));
cli.set_max_timeout(std::chrono::seconds(5));
set_max_timeout() is similar to curl’s --max-time option, but the deadline only shortens the waits for reading the response. Connecting and writing are bounded by the connection and write timeouts.
Set maximum payload length for reading a response body
cli.set_payload_max_length(1024 * 1024 * 512); // 512MB
A response body over the limit, also once decompressed, fails the request with Error::ExceedMaxPayloadSize.
Receive content with a content receiver
std::string body;
auto res = cli.Get("/large-data",
[&](const char *data, size_t data_length) {
body.append(data, data_length);
return true;
});
std::string body;
auto res = cli.Get(
"/stream", Headers(),
[&](const Response &response) {
// return 'false' if you want to cancel the request.
return response.status == StatusCode::OK_200;
},
[&](const char *data, size_t data_length) {
body.append(data, data_length);
return true; // return 'false' if you want to cancel the request.
});
Send content with a content provider
std::string body = ...;
auto res = cli.Post(
"/stream", body.size(),
[&](size_t offset, size_t length, DataSink &sink) {
sink.write(body.data() + offset, length);
return true; // return 'false' if you want to cancel the request.
},
"text/plain");
As on the server, write at most length bytes per call. The request fails with Error::Write if a call writes more, returns true without writing anything, or calls sink.done() before the whole content length is written.
Chunked transfer encoding
auto res = cli.Post(
"/stream",
[](size_t offset, DataSink &sink) {
sink.os << "chunked data 1";
sink.os << "chunked data 2";
sink.os << "chunked data 3";
sink.done();
return true; // return 'false' if you want to cancel the request.
},
"text/plain");
With Progress Callback
httplib::Client cli(url, port);
// prints: 0 / 000 bytes => 50% complete
auto res = cli.Get("/", [](size_t len, size_t total) {
printf("%lld / %lld bytes => %d%% complete\n",
len, total,
(int)(len*100/total));
return true; // return 'false' if you want to cancel the request.
}
);

Authentication
// Basic Authentication
cli.set_basic_auth("user", "pass");
// Digest Authentication
cli.set_digest_auth("user", "pass");
// Bearer Token Authentication
cli.set_bearer_token_auth("token");
A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
Proxy server support
cli.set_proxy("host", port);
// Basic Authentication
cli.set_proxy_basic_auth("user", "pass");
// Digest Authentication
cli.set_proxy_digest_auth("user", "pass");
// Bearer Token Authentication
cli.set_proxy_bearer_token_auth("pass");
A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
When the proxy refuses the CONNECT of an HTTPS request, the request fails with Error::ProxyConnection. Only a 407 Proxy Authentication Required comes back as the response, since any other answer from the proxy could be taken for the origin’s.
Bypass the proxy for specific hosts (NO_PROXY)
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
Each pattern is *, a hostname suffix, an IP literal, or a CIDR block.
Hostname matching is case-insensitive with a dot-boundary rule. See the
NO_PROXY cookbook
for details and for reading the variable from the environment.
set_proxy(), set_proxy_basic_auth(), set_proxy_bearer_token_auth(),
set_proxy_digest_auth() and set_no_proxy() are also available on
httplib::ws::WebSocketClient.
Range
httplib::Client cli("httpcan.org");
auto res = cli.Get("/range/32", httplib::Headers{
httplib::make_range_header({{1, 10}}) // 'Range: bytes=1-10'
});
// res->status should be 206.
// res->body should be "bcdefghijk".
httplib::make_range_header({{1, 10}, {20, -1}}) // 'Range: bytes=1-10, 20-'
httplib::make_range_header({{100, 199}, {500, 599}}) // 'Range: bytes=100-199, 500-599'
httplib::make_range_header({{0, 0}, {-1, 1}}) // 'Range: bytes=0-0, -1'
Keep-Alive connection
httplib::Client cli("localhost", 1234);
cli.Get("/hello"); // with "Connection: close"
cli.set_keep_alive(true);
cli.Get("/world");
cli.set_keep_alive(false);
cli.Get("/last-request"); // with "Connection: close"
Redirect
httplib::Client cli("yahoo.com");
auto res = cli.Get("/");
res->status; // 301
cli.set_follow_location(true);
res = cli.Get("/");
res->status; // 200
A URL with userinfo (http://user:pass@host/) is not supported, neither for a Client nor in a Location; use set_basic_auth() for the credentials. A Client constructed from a URL it cannot use, such as one with userinfo, a backslash in the authority or an invalid port, is not valid: is_valid() returns false, and every request fails with Error::Connection.
On a redirect to another origin (a different scheme, host or port), Authorization, Cookie and Proxy-Authorization are dropped along with the credentials set with set_basic_auth(), set_bearer_token_auth() and set_digest_auth(), and the client certificate is not presented. Other headers, the default ones included, go along (RFC 9110 §15.4), and so do the timeouts, the payload limit and the TLS verification settings. The TLS settings pass only from one HTTPS hop to the next: an HTTPS hop that follows a plain HTTP one starts over with the defaults, verifying against the system CAs with no verifier set. A 303 that turns a request into a GET drops its headers and body; only on the same origin are the default headers sent again.
Up to CPPHTTPLIB_REDIRECT_MAX_COUNT (20 by default) redirects are followed for a request; one more fails it with Error::ExceedRedirectCount. Interim 1xx responses before the final response are skipped, up to CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT (100 by default); one more fails the request with Error::Read.
Use a specific network interface
This feature is not available on Windows, Android, AIX and z/OS. The setting is ignored there.
cli.set_interface("eth0"); // Interface name, IP address or host name
The same method is available on httplib::ws::WebSocketClient.
Override the connection target for a hostname
set_direct_hostname_addr_map redirects where the socket connects, without
changing the identity of the request. The hostname the client was constructed
with keeps supplying the Host header, the SNI, and the name that the server
certificate is verified against, so this is a connection-level override only,
not a way to talk to a different origin.
httplib::Client cli("https://example.com");
// Connect to this IP address instead of resolving "example.com"
cli.set_direct_hostname_addr_map({{"example.com", "192.168.1.10"}});
A mapped value may be an IP literal or another hostname. An IP literal is used
as-is; anything else is resolved as a name, so a host that is only reachable
under a different name works too:
cli.set_direct_hostname_addr_map({{"example.com", "internal.example.lan"}});
An empty value is ignored, leaving the original hostname as the connection
target.
The direct map applies only when the client connects to the origin itself.
Through a proxy, use set_tunnel_hostname_addr_map: its value becomes the
CONNECT target (and that request’s Host) that the proxy is asked to connect
to (HTTPS and WebSocket). The Host header, the SNI and the certificate check
inside the tunnel keep the original hostname:
httplib::Client cli("https://sni.example");
cli.set_tunnel_hostname_addr_map({{"sni.example", "server.example"}});
cli.set_proxy("proxy.example", 3128);
// CONNECT server.example:443, SNI sni.example
The two maps are independent; to use the same target on both paths, set both.
They correspond to curl’s --resolve and --connect-to.
Neither map applies to the proxy’s own address (“direct” means not through a
proxy, as in a PAC file’s DIRECT). To connect to the proxy at a fixed
address, pass an IP literal to set_proxy().
set_hostname_addr_map is deprecated and works the same as
set_direct_hostname_addr_map.
These methods are also available on httplib::ws::WebSocketClient.
Automatic Path Encoding
The client automatically encodes special characters in URL paths by default:
httplib::Client cli("https://example.com");
// Automatic path encoding (default behavior)
cli.set_path_encode(true);
auto res = cli.Get("/path with spaces/file.txt"); // Automatically encodes spaces
// Disable automatic path encoding
cli.set_path_encode(false);
res = cli.Get("/already%20encoded/path"); // Use pre-encoded paths
set_path_encode(bool on) - Controls automatic encoding of special characters in URL paths
true (default): Automatically encodes spaces, plus signs, newlines, and other special characters
false: Sends paths as-is without encoding (useful for pre-encoded URLs)
A fragment (#...) in the path is never sent, whatever the setting.
On Windows systems with improperly configured IPv6 settings, using “localhost” as the hostname may cause significant connection delays (up to 2 seconds per request) due to DNS resolution issues. This affects both client and server operations. For better performance when connecting to local services, use “127.0.0.1” instead of “localhost”.
See: https://github.com/yhirose/cpp-httplib/issues/366#issuecomment-593004264
// May be slower on Windows due to DNS resolution delays
httplib::Client cli("localhost", 8080);
httplib::Server svr;
svr.listen("localhost", 8080);
// Faster alternative for local connections
httplib::Client cli("127.0.0.1", 8080);
httplib::Server svr;
svr.listen("127.0.0.1", 8080);
Headers, Params, FormFields, and FormFiles preserve the order entries were received (for a parsed request) or inserted (for one you build yourself). Earlier versions stored these in std::multimap or std::unordered_multimap, which either sorted entries by key or gave no ordering guarantee at all for repeated keys. RFC 9110 §5.3 and RFC 7578 §5.2 both require the original order to be preserved, so this is now guaranteed rather than incidental.
// A request with two Accept-Encoding lines...
// Accept-Encoding: gzip
// Accept-Encoding: br
// ...visits "gzip" before "br", not the other way around.
for (auto it = req.headers.equal_range("Accept-Encoding").first;
it != req.headers.end(); ++it) {
std::cout << it->second << std::endl;
}
// get_header_value(key, def, id) reaches a specific one directly.
auto second = req.get_header_value("Accept-Encoding", "", 1); // "br"
Headers matches field names case-insensitively, as before. Params, FormFields, and FormFiles are case-sensitive.
Iterators on these containers follow std::vector rules: inserting a new entry invalidates existing iterators. Code that keeps an iterator across a call to insert()/emplace() needs to re-fetch it afterward.
Payload Limit
The maximum payload body size is limited to 100MB by default for both server and client. You can change it with set_payload_max_length() or by defining CPPHTTPLIB_PAYLOAD_MAX_LENGTH at compile time. Setting it to 0 disables the limit entirely. On the client, a request made with a content receiver is not limited unless you call set_payload_max_length() yourself, so that a large download can be streamed without raising the limit first. The Stream API is limited either way.
Compression
The server can apply compression</std::endl></httplib::to_string></std::chrono::milliseconds></std::endl></std::endl></httplib::to_string>
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论