cpp-httplib

0

Описание

Языки

  • C++97%
  • CMake1,4%
  • C0,5%
  • Meson0,5%
  • Makefile0,4%
  • Остальные0,2%
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
README.md

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

CPPHTTPLIB_OPENSSL_SUPPORT
.
libssl
and
libcrypto
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_KEYCHAIN
.
CoreFoundation
and
Security
should be linked with
-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

Post
,
Put
,
Delete
and
Options
methods are also supported.

Bind a socket to multiple interfaces and any available port

Static File Server

The following are built-in mappings:

ExtensionMIME TypeExtensionMIME Type
csstext/cssmpgaaudio/mpeg
csvtext/csvwebaaudio/webm
txttext/plainwavaudio/wave
vtttext/vttotffont/otf
html, htmtext/htmlttffont/ttf
apngimage/apngwofffont/woff
avifimage/avifwoff2font/woff2
bmpimage/bmp7zapplication/x-7z-compressed
gifimage/gifatomapplication/atom+xml
pngimage/pngpdfapplication/pdf
svgimage/svg+xmlmjs, jstext/javascript
webpimage/webpjsonapplication/json
icoimage/x-iconrssapplication/rss+xml
tifimage/tifftarapplication/x-tar
tiffimage/tiffxhtml, xhtapplication/xhtml+xml
jpeg, jpgimage/jpegxsltapplication/xslt+xml
mp4video/mp4xmlapplication/xml
mpegvideo/mpeggzapplication/gzip
webmvideo/webmzipapplication/zip
mp3audio/mp3wasmapplication/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

catch (...)
block for a rethrown exception pointer, an uncaught exception will end up causing the server crash. Be careful!

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

100 Continue
response for an
Expect: 100-continue
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

ThreadPool
is used as the default task queue, with a default thread count of 8 or
std::thread::hardware_concurrency() - 1
, whichever is greater. You can change it with
CPPHTTPLIB_THREAD_POOL_COUNT
.

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

accept()
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

Result::error()
.

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

progress

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:

  • 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)

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

CPPHTTPLIB_ZLIB_SUPPORT
.
libz
should be linked.

Brotli Support

Brotli compression is available with

CPPHTTPLIB_BROTLI_SUPPORT
. Necessary libraries should be linked. Please see https://github.com/google/brotli for more detail.

Zstd Support

Zstd compression is available with

CPPHTTPLIB_ZSTD_SUPPORT
. Necessary libraries should be linked. Please see https://github.com/facebook/zstd for more detail.

Default
Accept-Encoding
value

The default

Accept-Encoding
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

Accept-Encoding
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

  • encode_uri(const std::string &value)
    - Encodes a full URI, preserving reserved characters like
    ://
    ,
    ?
    ,
    &
    ,
    =
  • decode_uri(const std::string &value)
    - Decodes a URI-encoded string
  • encode_uri_component(const std::string &value)
    - Encodes a URI component (query parameter, path segment), encoding all reserved characters
  • decode_uri_component(const std::string &value)
    - Decodes a URI component

Use

encode_uri()
for full URLs and
encode_uri_component()
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

/html
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

std::regex
implementations and affects the
dispatch_request()
method.

Consider using simpler patterns or path parameters to avoid this issue:

g++

g++ 4.8 and below cannot build this library since

<regex>
in the versions are broken.

Windows

Include

httplib.h
before
Windows.h
or include
Windows.h
by defining
WIN32_LEAN_AND_MEAN
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!