cpp-httplib/README.md

965 lines
25 KiB
Markdown
Raw Permalink Normal View History

2012-09-27 18:05:36 -07:00
cpp-httplib
===========
2012-09-21 19:38:33 -07:00
2019-09-19 21:43:02 -07:00
[![](https://github.com/yhirose/cpp-httplib/workflows/test/badge.svg)](https://github.com/yhirose/cpp-httplib/actions)
2019-01-11 18:31:06 -07:00
2020-01-21 21:45:21 -07:00
A C++11 single-file header-only cross platform HTTP/HTTPS library.
2012-09-22 21:41:21 -07:00
2020-12-19 09:12:44 -07:00
It's extremely easy to setup. 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.
2020-08-25 17:26:53 -07:00
2020-08-27 11:06:57 -07:00
Simple examples
---------------
2022-08-02 16:41:25 -07:00
#### Server (Multi-threaded)
2020-08-27 11:06:57 -07:00
```c++
2021-01-07 17:56:33 -07:00
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
2020-12-21 11:40:32 -07:00
// HTTP
2020-08-27 11:06:57 -07:00
httplib::Server svr;
2020-12-21 11:40:32 -07:00
// HTTPS
httplib::SSLServer svr;
2020-08-27 11:06:57 -07:00
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
res.set_content("Hello World!", "text/plain");
});
svr.listen("0.0.0.0", 8080);
```
2020-08-27 11:16:35 -07:00
#### Client
2020-08-27 11:06:57 -07:00
```c++
2021-01-07 17:56:33 -07:00
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "path/to/httplib.h"
2020-12-21 11:40:32 -07:00
// HTTP
httplib::Client cli("http://cpp-httplib-server.yhirose.repl.co");
2020-12-21 07:27:36 -07:00
2020-12-21 11:40:32 -07:00
// HTTPS
2020-12-21 07:27:36 -07:00
httplib::Client cli("https://cpp-httplib-server.yhirose.repl.co");
2020-08-27 11:06:57 -07:00
auto res = cli.Get("/hi");
2020-12-21 07:27:36 -07:00
res->status;
res->body;
2020-08-27 11:06:57 -07:00
```
2021-06-18 05:45:50 -07:00
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](https://www.openssl.org/policies/releasestrat.html) to get more information.
2023-04-04 07:17:59 -07:00
> [!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`.
2021-06-18 05:45:50 -07:00
```c++
#define CPPHTTPLIB_OPENSSL_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:1234"); // host
2022-11-10 06:27:30 -07:00
httplib::SSLClient cli("localhost", 1234); // host, port
2021-06-18 05:45:50 -07:00
// Use your CA bundle
cli.set_ca_cert_path("./ca-bundle.crt");
// Disable cert verification
cli.enable_server_certificate_verification(false);
2024-09-08 06:26:19 -07:00
// Disable host verification
cli.enable_server_host_verification(false);
2021-06-18 05:45:50 -07:00
```
> [!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.
2021-06-18 05:45:50 -07:00
2020-08-27 11:06:57 -07:00
Server
------
2015-02-06 20:43:06 -07:00
```c++
#include <httplib.h>
2015-02-06 20:43:06 -07:00
int main(void)
{
2020-02-14 19:49:09 -07:00
using namespace httplib;
2020-02-14 19:49:09 -07:00
Server svr;
svr.Get("/hi", [](const Request& req, Response& res) {
2020-02-14 19:49:09 -07:00
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) {
2020-02-14 19:49:09 -07:00
auto numbers = req.matches[1];
res.set_content(numbers, "text/plain");
});
2015-02-06 20:43:06 -07:00
// 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) {
2020-03-15 09:05:12 -07:00
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");
}
2020-03-15 09:05:12 -07:00
res.set_content(req.body, "text/plain");
});
svr.Get("/stop", [&](const Request& req, Response& res) {
svr.stop();
});
2019-07-23 05:05:51 -07:00
2020-02-14 19:49:09 -07:00
svr.listen("localhost", 1234);
2015-02-06 20:43:06 -07:00
}
```
2018-05-06 18:16:35 -07:00
`Post`, `Put`, `Delete` and `Options` methods are also supported.
2018-11-07 19:46:53 -07:00
### Bind a socket to multiple interfaces and any available port
```cpp
2018-11-09 21:30:58 -07:00
int port = svr.bind_to_any_port("0.0.0.0");
2018-11-07 19:46:53 -07:00
svr.listen_after_bind();
```
2017-11-25 09:59:28 -07:00
### Static File Server
```cpp
2020-01-31 18:40:33 -07:00
// Mount / to ./www directory
auto ret = svr.set_mount_point("/", "./www");
2020-01-06 15:13:31 -07:00
if (!ret) {
// The specified base directory doesn't exist...
}
2019-12-26 17:48:57 -07:00
2020-01-06 15:13:31 -07:00
// Mount /public to ./www directory
ret = svr.set_mount_point("/public", "./www");
2019-11-29 21:32:59 -07:00
2020-01-06 15:13:31 -07:00
// 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
2020-01-31 18:40:33 -07:00
// Remove mount /
ret = svr.remove_mount_point("/");
2020-02-01 07:24:42 -07:00
// Remove mount /public
ret = svr.remove_mount_point("/public");
2019-11-29 21:32:59 -07:00
```
```cpp
2020-01-06 15:13:31 -07:00
// 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");
2017-11-25 09:59:28 -07:00
```
2019-12-26 17:48:57 -07:00
The followings are built-in mappings:
2020-12-19 20:43:31 -07:00
| 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 | application/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 |
2020-01-31 18:40:33 -07:00
> [!WARNING]
> These static file server methods are not thread-safe.
2023-07-05 05:45:05 -07:00
2022-03-17 05:38:00 -07:00
### File request handler
```cpp
// The handler is called right before the response is sent to a client
svr.set_file_request_handler([](const Request &req, Response &res) {
...
});
```
2017-11-25 09:59:28 -07:00
### Logging
```cpp
svr.set_logger([](const auto& req, const auto& res) {
2020-02-14 19:49:09 -07:00
your_logger(req, res);
2017-11-25 09:59:28 -07:00
});
```
2020-02-10 22:26:15 -07:00
### Error handler
2017-11-25 09:59:28 -07:00
```cpp
svr.set_error_handler([](const auto& req, auto& res) {
2020-02-14 19:49:09 -07:00
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");
2017-11-25 09:59:28 -07:00
});
```
### Exception handler
The exception handler gets called if a user routing handler throws an error.
```cpp
2022-07-15 14:32:38 -07:00
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];
2022-07-15 14:32:38 -07:00
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;
});
```
> [!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!
2022-07-15 14:32:38 -07:00
2021-01-07 17:00:24 -07:00
### Pre routing handler
```cpp
2021-12-10 20:33:59 -07:00
svr.set_pre_routing_handler([](const auto& req, auto& res) {
2021-01-07 17:00:24 -07:00
if (req.path == "/hello") {
res.set_content("world", "text/html");
2021-01-27 09:59:24 -07:00
return Server::HandlerResponse::Handled;
2021-01-07 17:00:24 -07:00
}
2021-01-27 09:59:24 -07:00
return Server::HandlerResponse::Unhandled;
2021-01-07 17:00:24 -07:00
});
```
### Post routing handler
```cpp
svr.set_post_routing_handler([](const auto& req, auto& res) {
res.set_header("ADDITIONAL_HEADER", "value");
});
```
2017-12-12 20:22:10 -07:00
### 'multipart/form-data' POST data
2017-12-05 17:30:13 -07:00
```cpp
2018-05-06 18:16:35 -07:00
svr.Post("/multipart", [&](const auto& req, auto& res) {
2020-02-14 19:49:09 -07:00
auto size = req.files.size();
auto ret = req.has_file("name1");
const auto& file = req.get_file_value("name1");
2020-02-14 19:49:09 -07:00
// file.filename;
// file.content_type;
// file.content;
});
```
2020-12-19 09:12:44 -07:00
### Receive content with a content receiver
2019-11-29 21:32:59 -07:00
```cpp
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
MultipartFormDataItems files;
content_reader(
2019-12-12 20:44:54 -07:00
[&](const MultipartFormData &file) {
files.push_back(file);
return true;
},
2019-12-12 20:44:54 -07:00
[&](const char *data, size_t data_length) {
files.back().content.append(data, data_length);
return true;
});
} else {
std::string body;
content_reader([&](const char *data, size_t data_length) {
body.append(data, data_length);
return true;
});
}
2019-11-29 21:32:59 -07:00
});
```
2020-12-19 09:12:44 -07:00
### Send content with the content provider
2020-02-14 19:49:09 -07:00
```cpp
2020-05-07 18:13:45 -07:00
const size_t DATA_CHUNK_SIZE = 4;
2020-02-14 19:49:09 -07:00
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; });
2020-02-14 19:49:09 -07:00
});
```
2020-08-16 17:49:54 -07:00
Without content length:
```cpp
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.
});
2020-08-16 17:49:54 -07:00
});
```
### Chunked transfer encoding
```cpp
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.
}
);
});
```
2020-01-17 21:21:42 -07:00
2023-03-11 14:57:51 -07:00
With trailer:
```cpp
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;
}
);
2023-03-11 14:57:51 -07:00
});
```
2024-09-06 20:51:39 -07:00
### Send file content
```cpp
svr.Get("/content", [&](const Request &req, Response &res) {
res.set_file_content("./path/to/conent.html");
});
svr.Get("/content", [&](const Request &req, Response &res) {
res.set_file_content("./path/to/conent", "text/html");
});
```
2020-05-23 16:08:17 -07:00
### 'Expect: 100-continue' handler
2020-12-19 09:12:44 -07:00
By default, the server sends a `100 Continue` response for an `Expect: 100-continue` header.
2020-05-23 16:08:17 -07:00
```cpp
// Send a '417 Expectation Failed' response.
svr.set_expect_100_continue_handler([](const Request &req, Response &res) {
return StatusCode::ExpectationFailed_417;
2020-05-23 16:08:17 -07:00
});
```
```cpp
// 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;
2020-05-23 16:08:17 -07:00
});
```
### Keep-Alive connection
```cpp
svr.set_keep_alive_max_count(2); // Default is 5
svr.set_keep_alive_timeout(10); // Default is 5
2020-05-23 16:08:17 -07:00
```
### Timeout
```c++
svr.set_read_timeout(5, 0); // 5 seconds
svr.set_write_timeout(5, 0); // 5 seconds
svr.set_idle_interval(0, 100000); // 100 milliseconds
```
2020-12-19 09:12:44 -07:00
### Set maximum payload length for reading a request body
2020-05-23 16:08:17 -07:00
```c++
svr.set_payload_max_length(1024 * 1024 * 512); // 512MB
```
> [!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`.
2023-12-17 20:04:36 -07:00
2020-01-17 21:21:42 -07:00
### Server-Sent Events
2020-07-25 08:24:06 -07:00
Please see [Server example](https://github.com/yhirose/cpp-httplib/blob/master/example/ssesvr.cc) and [Client example](https://github.com/yhirose/cpp-httplib/blob/master/example/ssecli.cc).
2019-12-02 07:50:52 -07:00
### Default thread pool support
2019-08-05 02:17:40 -07:00
2020-09-15 07:11:46 -07:00
`ThreadPool` is used as a **default** task queue, and the default thread count is 8, or `std::thread::hardware_concurrency()`. You can change it with `CPPHTTPLIB_THREAD_POOL_COUNT`.
2019-08-05 02:17:40 -07:00
2020-09-15 07:11:46 -07:00
If you want to set the thread count at runtime, there is no convenient way... But here is how.
2019-08-05 02:17:40 -07:00
2020-09-15 07:11:46 -07:00
```cpp
svr.new_task_queue = [] { return new ThreadPool(12); };
2020-09-15 07:11:46 -07:00
```
2019-08-05 02:17:40 -07:00
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.
```cpp
svr.new_task_queue = [] { return new ThreadPool(/*num_threads=*/12, /*max_queued_requests=*/18); };
```
Default limit is 0 (unlimited). Once the limit is reached, the listener
will shutdown the client connection.
2019-08-05 02:17:40 -07:00
### Override the default thread pool with yours
2020-09-15 07:11:46 -07:00
You can supply your own thread pool implementation according to your need.
2019-08-05 02:17:40 -07:00
```cpp
class YourThreadPoolTaskQueue : public TaskQueue {
public:
YourThreadPoolTaskQueue(size_t n) {
pool_.start_with_thread_count(n);
}
2019-08-05 02:17:40 -07:00
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);
2019-08-05 02:17:40 -07:00
}
virtual void shutdown() override {
pool_.shutdown_gracefully();
}
2019-08-05 02:17:40 -07:00
private:
YourThreadPool pool_;
};
svr.new_task_queue = [] {
return new YourThreadPoolTaskQueue(12);
};
```
2020-08-27 11:06:57 -07:00
Client
------
2015-02-06 20:43:06 -07:00
```c++
#include <httplib.h>
#include <iostream>
2015-02-06 20:43:06 -07:00
int main(void)
{
2020-02-14 19:49:09 -07:00
httplib::Client cli("localhost", 1234);
2020-08-08 17:50:24 -07:00
if (auto res = cli.Get("/hi")) {
if (res->status == StatusCode::OK_200) {
2020-08-08 17:50:24 -07:00
std::cout << res->body << std::endl;
}
} else {
auto err = res.error();
std::cout << "HTTP error: " << httplib::to_string(err) << std::endl;
2020-02-14 19:49:09 -07:00
}
2015-02-06 20:43:06 -07:00
}
```
> [!TIP]
> Constructor with scheme-host-port string is now supported!
2020-07-29 19:59:26 -07:00
```c++
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");
2020-12-21 07:27:36 -07:00
httplib::SSLClient cli("localhost");
2020-07-29 19:59:26 -07:00
```
2020-10-27 17:35:56 -07:00
### Error code
Here is the list of errors from `Result::error()`.
```c++
enum Error {
Success = 0,
Unknown,
Connection,
BindIPAddress,
Read,
Write,
ExceedRedirectCount,
Canceled,
SSLConnection,
SSLLoadingCerts,
SSLServerVerification,
UnsupportedMultipartBoundaryChars,
Compression,
ConnectionTimeout,
2020-10-27 17:35:56 -07:00
};
```
2019-07-23 05:05:51 -07:00
### GET with HTTP headers
```c++
2020-02-14 19:49:09 -07:00
httplib::Headers headers = {
2024-11-16 07:45:04 -07:00
{ "Hello", "World!" }
2020-02-14 19:49:09 -07:00
};
auto res = cli.Get("/hi", headers);
2019-07-23 05:05:51 -07:00
```
2020-08-03 20:37:05 -07:00
or
```c++
2024-11-16 07:45:04 -07:00
auto res = cli.Get("/hi", {{"Hello", "World!"}});
2023-02-01 17:11:11 -07:00
```
or
```c++
2020-08-03 20:37:05 -07:00
cli.set_default_headers({
2024-11-16 07:45:04 -07:00
{ "Hello", "World!" }
2020-08-03 20:37:05 -07:00
});
auto res = cli.Get("/hi");
```
2019-07-23 05:05:51 -07:00
2017-12-05 17:30:13 -07:00
### POST
```c++
2018-05-06 18:16:35 -07:00
res = cli.Post("/post", "text", "text/plain");
res = cli.Post("/person", "name=john1&note=coder", "application/x-www-form-urlencoded");
2017-12-05 17:30:13 -07:00
```
### POST with parameters
```c++
2018-05-09 04:17:45 -07:00
httplib::Params params;
2018-05-18 13:43:08 -07:00
params.emplace("name", "john");
params.emplace("note", "coder");
auto res = cli.Post("/post", params);
```
or
```c++
httplib::Params params{
{ "name", "john" },
{ "note", "coder" }
};
2018-05-06 18:16:35 -07:00
auto res = cli.Post("/post", params);
```
2019-07-23 06:52:12 -07:00
### POST with Multipart Form Data
```c++
2020-02-14 19:49:09 -07:00
httplib::MultipartFormDataItems 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);
2019-07-23 06:52:12 -07:00
```
2018-05-06 18:16:35 -07:00
### PUT
```c++
2018-05-09 04:17:45 -07:00
res = cli.Put("/resource/foo", "text", "text/plain");
2018-05-06 18:16:35 -07:00
```
### DELETE
```c++
res = cli.Delete("/resource/foo");
```
### OPTIONS
```c++
res = cli.Options("*");
res = cli.Options("/resource/foo");
2017-12-05 17:30:13 -07:00
```
2020-05-23 16:08:17 -07:00
### Timeout
```c++
2020-05-23 16:08:17 -07:00
cli.set_connection_timeout(0, 300000); // 300 milliseconds
cli.set_read_timeout(5, 0); // 5 seconds
cli.set_write_timeout(5, 0); // 5 seconds
```
2020-05-23 16:08:17 -07:00
2020-12-19 09:12:44 -07:00
### Receive content with a content receiver
2020-05-13 18:48:14 -07:00
2020-07-25 08:20:57 -07:00
```c++
std::string body;
auto res = cli.Get("/large-data",
[&](const char *data, size_t data_length) {
body.append(data, data_length);
return true;
2020-07-25 08:20:57 -07:00
});
```
2020-05-13 18:48:14 -07:00
```cpp
std::string body;
2020-07-25 08:24:06 -07:00
2020-05-13 18:48:14 -07:00
auto res = cli.Get(
"/stream", Headers(),
[&](const Response &response) {
EXPECT_EQ(StatusCode::OK_200, response.status);
return true; // return 'false' if you want to cancel the request.
2020-05-13 18:48:14 -07:00
},
[&](const char *data, size_t data_length) {
body.append(data, data_length);
return true; // return 'false' if you want to cancel the request.
2020-05-13 18:48:14 -07:00
});
```
2020-12-19 09:12:44 -07:00
### Send content with a content provider
2020-05-13 18:48:14 -07:00
```cpp
std::string body = ...;
2020-07-25 08:24:06 -07:00
2020-11-22 07:22:40 -07:00
auto res = cli.Post(
2020-05-13 18:48:14 -07:00
"/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.
2020-05-13 18:48:14 -07:00
},
"text/plain");
```
2020-11-22 07:22:40 -07:00
### Chunked transfer encoding
```cpp
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.
2020-11-22 07:22:40 -07:00
},
"text/plain");
```
### With Progress Callback
```cpp
httplib::Client cli(url, port);
// prints: 0 / 000 bytes => 50% complete
2020-08-08 17:50:24 -07:00
auto res = cli.Get("/", [](uint64_t len, uint64_t total) {
printf("%lld / %lld bytes => %d%% complete\n",
len, total,
(int)(len*100/total));
2020-08-08 17:50:24 -07:00
return true; // return 'false' if you want to cancel the request.
}
);
```
2017-12-12 20:22:10 -07:00
![progress](https://user-images.githubusercontent.com/236374/33138910-495c4ecc-cf86-11e7-8693-2fc6d09615c4.gif)
2019-12-10 10:06:29 -07:00
### Authentication
2017-12-12 20:20:40 -07:00
2019-12-20 21:12:24 -07:00
```cpp
// Basic Authentication
cli.set_basic_auth("user", "pass");
// Digest Authentication
cli.set_digest_auth("user", "pass");
2020-07-31 15:54:53 -07:00
// Bearer Token Authentication
cli.set_bearer_token_auth("token");
2019-12-20 21:12:24 -07:00
```
> [!NOTE]
> OpenSSL is required for Digest Authentication.
2019-12-20 21:12:24 -07:00
### Proxy server support
2019-12-10 11:14:23 -07:00
2017-12-12 20:20:40 -07:00
```cpp
2019-12-20 21:12:24 -07:00
cli.set_proxy("host", port);
// Basic Authentication
cli.set_proxy_basic_auth("user", "pass");
// Digest Authentication
cli.set_proxy_digest_auth("user", "pass");
2020-07-31 15:54:53 -07:00
// Bearer Token Authentication
cli.set_proxy_bearer_token_auth("pass");
2019-07-19 08:38:06 -07:00
```
2017-12-12 20:20:40 -07:00
> [!NOTE]
> OpenSSL is required for Digest Authentication.
2019-12-20 21:12:24 -07:00
2019-07-19 08:38:06 -07:00
### Range
```cpp
httplib::Client cli("httpbin.org");
2017-12-12 20:20:40 -07:00
2019-07-19 08:38:06 -07:00
auto res = cli.Get("/range/32", {
httplib::make_range_header({{1, 10}}) // 'Range: bytes=1-10'
2019-07-19 08:38:06 -07:00
});
2017-12-12 20:20:40 -07:00
// res->status should be 206.
// res->body should be "bcdefghijk".
```
```cpp
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'
```
2019-08-31 15:01:45 -07:00
### Keep-Alive connection
```cpp
2020-06-16 14:46:23 -07:00
httplib::Client cli("localhost", 1234);
2019-08-31 15:01:45 -07:00
2020-06-16 14:46:23 -07:00
cli.Get("/hello"); // with "Connection: close"
2019-08-31 15:01:45 -07:00
2020-06-16 14:46:23 -07:00
cli.set_keep_alive(true);
cli.Get("/world");
2020-05-07 18:13:45 -07:00
2020-06-16 14:46:23 -07:00
cli.set_keep_alive(false);
cli.Get("/last-request"); // with "Connection: close"
2019-08-31 15:01:45 -07:00
```
2019-09-05 21:26:57 -07:00
### Redirect
```cpp
httplib::Client cli("yahoo.com");
2019-09-06 15:16:42 -07:00
2019-09-06 15:16:42 -07:00
auto res = cli.Get("/");
2019-09-06 15:16:42 -07:00
res->status; // 301
2019-12-13 04:56:00 -07:00
cli.set_follow_location(true);
2019-09-06 15:16:42 -07:00
res = cli.Get("/");
2019-09-06 15:16:42 -07:00
res->status; // 200
2019-09-05 21:26:57 -07:00
```
2020-12-18 13:12:21 -07:00
### Use a specific network interface
2019-12-15 15:55:08 -07:00
> [!NOTE]
> This feature is not available on Windows, yet.
2019-12-15 18:31:36 -07:00
2019-12-15 15:55:08 -07:00
```cpp
cli.set_interface("eth0"); // Interface name, IP address or host name
```
2020-07-25 17:53:38 -07:00
Compression
-----------
2017-12-28 18:47:52 -07:00
2020-12-19 09:12:44 -07:00
The server can apply compression to the following MIME type contents:
2017-12-28 18:47:52 -07:00
2020-07-25 17:53:38 -07:00
* all text types except text/event-stream
2017-12-28 18:47:52 -07:00
* image/svg+xml
* application/javascript
* application/json
* application/xml
* application/xhtml+xml
2020-07-25 17:53:38 -07:00
### 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.
2024-11-16 07:45:04 -07:00
### Default `Accept-Encoding` value
The default `Acdcept-Encoding` value contains all possible compression types. So, the following two examples are same.
```c++
res = cli.Get("/resource/foo");
res = cli.Get("/resource/foo", {{"Accept-Encoding", "gzip, deflate, br"}});
```
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.
```c++
res = cli.Get("/resource/foo", {{"Accept-Encoding", ""}});
```
2020-05-26 15:20:56 -07:00
### Compress request body on client
```c++
2019-12-13 04:56:00 -07:00
cli.set_compress(true);
res = cli.Post("/resource/foo", "...", "text/plain");
```
2020-05-26 15:20:56 -07:00
### Compress response body on client
```c++
cli.set_decompress(false);
2024-11-16 07:45:04 -07:00
res = cli.Get("/resource/foo");
2020-05-26 15:20:56 -07:00
res->body; // Compressed data
2024-11-16 07:45:04 -07:00
2020-05-26 15:20:56 -07:00
```
2021-10-03 15:37:46 -07:00
Use `poll` instead of `select`
------------------------------
`select` system call is used as default since it's more widely supported. If you want to let cpp-httplib use `poll` instead, you can do so with `CPPHTTPLIB_USE_POLL`.
Unix Domain Socket Support
--------------------------
Unix Domain Socket support is available on Linux and macOS.
```c++
// Server
httplib::Server svr("./my-socket.sock");
svr.set_address_family(AF_UNIX).listen("./my-socket.sock", 80);
// Client
httplib::Client cli("./my-socket.sock");
cli.set_address_family(AF_UNIX);
```
"my-socket.sock" can be a relative path or an absolute path. You 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.
2021-10-03 15:37:46 -07:00
2019-12-14 22:21:32 -07:00
Split httplib.h into .h and .cc
-------------------------------
```console
$ ./split.py -h
usage: split.py [-h] [-e EXTENSION] [-o OUT]
This script splits httplib.h into .h and .cc parts.
optional arguments:
-h, --help show this help message and exit
-e EXTENSION, --extension EXTENSION
extension of the implementation file (default: cc)
-o OUT, --out OUT where to write the files (default: out)
$ ./split.py
Wrote out/httplib.h and out/httplib.cc
2019-12-14 22:21:32 -07:00
```
2024-08-31 14:42:43 -07:00
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.
```bash
> docker build -t cpp-httplib-server .
...
2024-09-04 09:23:48 -07:00
> docker run --rm -it -p 8080:80 -v ./docker/html:/html cpp-httplib-server
Serving HTTP on 0.0.0.0 port 80 ...
192.168.65.1 - - [31/Aug/2024:21:33:56 +0000] "GET / HTTP/1.1" 200 599 "-" "curl/8.7.1"
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET / HTTP/1.1" 200 599 "-" "Mozilla/5.0 ..."
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
```
From Docker Hub
```bash
> docker run --rm -it -p 8080:80 -v ./docker/html:/html yhirose4dockerhub/cpp-httplib-server
...
2024-08-31 14:42:43 -07:00
> docker run --init --rm -it -p 8080:80 -v ./docker/html:/html cpp-httplib-server
Serving HTTP on 0.0.0.0 port 80 ...
192.168.65.1 - - [31/Aug/2024:21:33:56 +0000] "GET / HTTP/1.1" 200 599 "-" "curl/8.7.1"
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET / HTTP/1.1" 200 599 "-" "Mozilla/5.0 ..."
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
```
2019-01-15 06:24:17 -07:00
NOTE
----
2020-03-17 15:01:49 -07:00
### g++
g++ 4.8 and below cannot build this library since `<regex>` in the versions are [broken](https://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions).
2019-01-15 06:24:17 -07:00
2020-03-17 15:01:49 -07:00
### Windows
Include `httplib.h` before `Windows.h` or include `Windows.h` by defining `WIN32_LEAN_AND_MEAN` beforehand.
```cpp
#include <httplib.h>
#include <Windows.h>
2020-03-17 15:01:49 -07:00
```
```cpp
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <httplib.h>
```
> [!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 2013 or lower, and Cygwin and MSYS2 including MinGW are neither supported nor tested.
2020-04-18 13:36:36 -07:00
2017-12-20 15:27:36 -07:00
License
-------
2024-01-29 06:53:01 -07:00
MIT license (© 2024 Yuji Hirose)
2020-01-26 16:33:51 -07:00
Special Thanks To
-----------------
2020-03-17 15:01:49 -07:00
[These folks](https://github.com/yhirose/cpp-httplib/graphs/contributors) made great contributions to polish this library to totally another level from a simple toy!