cpp-httplib
Описание
Языки
- C++97%
- CMake1,4%
- C0,5%
- Meson0,5%
- Makefile0,4%
- Остальные0,2%
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!
Important
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.
Simple examples
Server (Multi-threaded)
Client
SSL Support
SSL support is available with . and should be linked.
Note
cpp-httplib currently supports only version 3.0 or later. Please see this page to get more information.
Tip
For macOS: cpp-httplib now can use system certs with
.CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAINandCoreFoundationshould be linked withSecurity.-framework
Note
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.
SSL Error Handling
When SSL operations fail, cpp-httplib provides detailed error information through two separate error fields:
Server
, , and methods are also supported.
Bind a socket to multiple interfaces and any available port
Static File Server
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 | 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 |
Warning
These static file server methods are not thread-safe.
File request 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 successful HTTP requests and responses:
Pre-compression Logging
You can also set a pre-compression logger to capture request/response data before compression is applied:
The pre-compression logger is only called when compression would be applied. For responses without compression, only the access logger is called.
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.
Error handler
Exception handler
The exception handler gets called if a user routing handler throws an error.
Caution
if you don't provide the
block for a rethrown exception pointer, an uncaught exception will end up causing the server crash. Be careful!catch (...)
Pre routing handler
Post routing handler
Pre request handler
Form data handling
URL-encoded form data ('application/x-www-form-urlencoded')
'multipart/form-data' POST data
Receive content with a content receiver
Send content with the content provider
Without content length:
Chunked transfer encoding
With trailer:
Send file content
'Expect: 100-continue' handler
By default, the server sends a response for an header.
Keep-Alive connection
Timeout
Set maximum payload length for reading a request body
Note
When the request body content type is 'www-form-urlencoded', the actual payload length shouldn't exceed
.CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
Server-Sent Events
Please see Server example and Client example.
Default thread pool support
is used as the default task queue, with a default thread count of 8 or , whichever is greater. You can change it with .
If you want to set the thread count at runtime, there is no convenient way... But here is how.
You can also provide an optional parameter to limit the maximum number
of pending requests, i.e. requests ed by the listener but
still waiting to be serviced by worker threads.
Default limit is 0 (unlimited). Once the limit is reached, the listener will shutdown the client connection.
Override the default thread pool with yours
You can supply your own thread pool implementation according to your need.
Client
Tip
Constructor with scheme-host-port string is now supported!
Error code
Here is the list of errors from .
Client Logging
Access Logging
Error Logging
GET with HTTP headers
or
or
POST
POST with parameters
or
POST with Multipart Form Data
PUT
DELETE
OPTIONS
Timeout
Receive content with a content receiver
Send content with a content provider
Chunked transfer encoding
With Progress Callback

Authentication
Note
OpenSSL is required for Digest Authentication.
Proxy server support
Note
OpenSSL is required for Digest Authentication.
Range
Keep-Alive connection
Redirect
Use a specific network interface
Note
This feature is not available on Windows, yet.
Automatic Path Encoding
The client automatically encodes special characters in URL paths by default:
- Controls automatic encoding of special characters in URL pathsset_path_encode(bool on)(default): Automatically encodes spaces, plus signs, newlines, and other special characterstrue: Sends paths as-is without encoding (useful for pre-encoded URLs)false
Performance Note for Local Connections
Warning
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
Compression
The server can apply compression to the following MIME type contents:
- all text types except text/event-stream
- image/svg+xml
- application/javascript
- application/json
- application/xml
- application/protobuf
- application/xhtml+xml
Zlib Support
'gzip' compression is available with . should be linked.
Brotli Support
Brotli compression is available with . Necessary libraries should be linked.
Please see https://github.com/google/brotli for more detail.
Zstd Support
Zstd compression is available with . Necessary libraries should be linked.
Please see https://github.com/facebook/zstd for more detail.
Default Accept-Encoding value
The default value contains all possible compression types. So, the following two examples are same.
If we don't want a response without compression, we have to set to an empty string. This behavior is similar to curl.
Compress request body on client
Compress response body on client
Unix Domain Socket Support
Unix Domain Socket support is available on Linux and macOS.
"my-socket.sock" can be a relative path or an absolute path. Your application must have the appropriate permissions for the path. You can also use an abstract socket address on Linux. To use an abstract socket address, prepend a null byte ('\x00') to the path.
This library automatically sets the Host header to "localhost" for Unix socket connections, similar to curl's behavior:
URI Encoding/Decoding Utilities
cpp-httplib provides utility functions for URI encoding and decoding:
Functions
- Encodes a full URI, preserving reserved characters likeencode_uri(const std::string &value),://,?,&=- Decodes a URI-encoded stringdecode_uri(const std::string &value)- Encodes a URI component (query parameter, path segment), encoding all reserved charactersencode_uri_component(const std::string &value)- Decodes a URI componentdecode_uri_component(const std::string &value)
Use for full URLs and for individual query parameters or path segments.
Split httplib.h into .h and .cc
Dockerfile for Static HTTP Server
Dockerfile for static HTTP server is available. Port number of this HTTP server is 80, and it serves static files from directory in the container.
From Docker Hub
NOTE
Regular Expression Stack Overflow
Caution
When using complex regex patterns in route handlers, be aware that certain patterns may cause stack overflow during pattern matching. This is a known issue with
implementations and affects thestd::regexmethod.dispatch_request()Consider using simpler patterns or path parameters to avoid this issue:
g++
g++ 4.8 and below cannot build this library since in the versions are broken.
Windows
Include before or include by defining beforehand.
Note
cpp-httplib officially supports only the latest Visual Studio. It might work with former versions of Visual Studio, but I can no longer verify it. Pull requests are always welcome for the older versions of Visual Studio unless they break the C++11 conformance.
Note
Windows 8 or lower, Visual Studio 2015 or lower, and Cygwin and MSYS2 including MinGW are neither supported nor tested.
License
MIT license (© 2025 Yuji Hirose)
Special Thanks To
These folks made great contributions to polish this library to totally another level from a simple toy!