mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-14 10:29:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c419c904da | ||
|
|
878ba41099 | ||
|
|
941745c33d | ||
|
|
11daa99c86 | ||
|
|
cbaf751da1 | ||
|
|
33d84a12b6 | ||
|
|
5107381963 | ||
|
|
0acbee16dc | ||
|
|
1f12bbaabb | ||
|
|
5189edc52e | ||
|
|
fee592c2c2 | ||
|
|
885ed54b10 | ||
|
|
c95d799180 | ||
|
|
bef278e0d2 | ||
|
|
05f7478523 | ||
|
|
f6aee694e2 | ||
|
|
8aa547e4a1 | ||
|
|
84ff13ec47 | ||
|
|
8f094fe292 | ||
|
|
00afaaed6a | ||
|
|
e803f5e413 | ||
|
|
57b8aca6da | ||
|
|
213029685a | ||
|
|
17eeb18feb | ||
|
|
edc9760005 | ||
|
|
6d1049462d | ||
|
|
4fcbc08f2d | ||
|
|
d59f3e438c | ||
|
|
09fa6820fe | ||
|
|
438319cfcb | ||
|
|
eda9a10bfe | ||
|
|
cf3693cb5c | ||
|
|
4fd9ae8f42 | ||
|
|
3d40dfc727 | ||
|
|
dd71728110 | ||
|
|
7255a7e979 | ||
|
|
8a3abfb597 | ||
|
|
10aadd57f7 | ||
|
|
43863e1f67 | ||
|
|
0db1df7cf2 | ||
|
|
639391ad7f | ||
|
|
0715c2739e | ||
|
|
3330d0eb06 | ||
|
|
c1c2b1f4b4 | ||
|
|
e11dbec7b3 | ||
|
|
174bce5ccf | ||
|
|
57c4f7f385 | ||
|
|
2fb2dbbe1e | ||
|
|
8b6ab24159 | ||
|
|
5a202d3d5f | ||
|
|
4f3f9ef19b | ||
|
|
6d59d1e2df | ||
|
|
9386b25dd7 |
No files matched your search
+21
-3
@@ -15,7 +15,7 @@
|
||||
* HTTPLIB_REQUIRE_BROTLI (default off)
|
||||
* HTTPLIB_REQUIRE_ZSTD (default off)
|
||||
* HTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES (default off)
|
||||
* HTTPLIB_USE_NON_BLOCKING_GETADDRINFO (default on)
|
||||
* HTTPLIB_USE_NON_BLOCKING_GETADDRINFO (default on when supported)
|
||||
* HTTPLIB_COMPILE (default off)
|
||||
* HTTPLIB_INSTALL (default on)
|
||||
* HTTPLIB_SHARED (default off) builds as a shared library (if HTTPLIB_COMPILE is ON)
|
||||
@@ -181,6 +181,24 @@ if(HTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES)
|
||||
set(HTTPLIB_IS_USING_MACOSX_AUTOMATIC_ROOT_CERTIFICATES FALSE)
|
||||
endif()
|
||||
set(HTTPLIB_IS_USING_NON_BLOCKING_GETADDRINFO ${HTTPLIB_USE_NON_BLOCKING_GETADDRINFO})
|
||||
if(HTTPLIB_IS_USING_NON_BLOCKING_GETADDRINFO AND WIN32)
|
||||
include(CheckCXXSymbolExists)
|
||||
|
||||
set(_httplib_cmake_required_definitions ${CMAKE_REQUIRED_DEFINITIONS})
|
||||
set(_httplib_cmake_required_libraries ${CMAKE_REQUIRED_LIBRARIES})
|
||||
list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_WIN32_WINNT=0x0A00)
|
||||
list(APPEND CMAKE_REQUIRED_LIBRARIES ws2_32)
|
||||
check_cxx_symbol_exists(GetAddrInfoExCancel "winsock2.h;ws2tcpip.h" HTTPLIB_HAVE_GETADDRINFOEXCANCEL)
|
||||
set(CMAKE_REQUIRED_DEFINITIONS ${_httplib_cmake_required_definitions})
|
||||
set(CMAKE_REQUIRED_LIBRARIES ${_httplib_cmake_required_libraries})
|
||||
unset(_httplib_cmake_required_definitions)
|
||||
unset(_httplib_cmake_required_libraries)
|
||||
|
||||
if(NOT HTTPLIB_HAVE_GETADDRINFOEXCANCEL)
|
||||
set(HTTPLIB_IS_USING_NON_BLOCKING_GETADDRINFO FALSE)
|
||||
message(WARNING "GetAddrInfoExCancel is unavailable; disabling non-blocking getaddrinfo.")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Threads needed for <thread> on some systems, and for <pthread.h> on Linux
|
||||
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
|
||||
@@ -367,7 +385,7 @@ target_link_libraries(${PROJECT_NAME} ${_INTERFACE_OR_PUBLIC}
|
||||
# Needed for API from MacOS Security framework
|
||||
"$<$<AND:$<PLATFORM_ID:Darwin>,$<BOOL:${HTTPLIB_IS_USING_OPENSSL}>,$<BOOL:${HTTPLIB_IS_USING_MACOSX_AUTOMATIC_ROOT_CERTIFICATES}>>:-framework CFNetwork -framework CoreFoundation -framework Security>"
|
||||
# Needed for non-blocking getaddrinfo on MacOS
|
||||
"$<$<AND:$<PLATFORM_ID:Darwin>,$<BOOL:${HTTPLIB_USE_NON_BLOCKING_GETADDRINFO}>>:-framework CFNetwork -framework CoreFoundation>"
|
||||
"$<$<AND:$<PLATFORM_ID:Darwin>,$<BOOL:${HTTPLIB_IS_USING_NON_BLOCKING_GETADDRINFO}>>:-framework CFNetwork -framework CoreFoundation>"
|
||||
# Can't put multiple targets in a single generator expression or it bugs out.
|
||||
$<$<BOOL:${HTTPLIB_IS_USING_BROTLI}>:Brotli::common>
|
||||
$<$<BOOL:${HTTPLIB_IS_USING_BROTLI}>:Brotli::encoder>
|
||||
@@ -390,7 +408,7 @@ target_compile_definitions(${PROJECT_NAME} ${_INTERFACE_OR_PUBLIC}
|
||||
$<$<BOOL:${HTTPLIB_IS_USING_WOLFSSL}>:CPPHTTPLIB_WOLFSSL_SUPPORT>
|
||||
$<$<BOOL:${HTTPLIB_IS_USING_MBEDTLS}>:CPPHTTPLIB_MBEDTLS_SUPPORT>
|
||||
$<$<AND:$<PLATFORM_ID:Darwin>,$<BOOL:${HTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES}>>:CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES>
|
||||
$<$<BOOL:${HTTPLIB_USE_NON_BLOCKING_GETADDRINFO}>:CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO>
|
||||
$<$<BOOL:${HTTPLIB_IS_USING_NON_BLOCKING_GETADDRINFO}>:CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO>
|
||||
)
|
||||
|
||||
# CMake configuration files installation directory
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ sse.on_error([](httplib::Error err) { });
|
||||
#### Configuration
|
||||
|
||||
```cpp
|
||||
// Set reconnect interval (default: 3000ms)
|
||||
// Set reconnect interval (default: 3000ms, minimum: 100ms)
|
||||
sse.set_reconnect_interval(5000);
|
||||
|
||||
// Set max reconnect attempts (default: 0 = unlimited)
|
||||
|
||||
+16
-11
@@ -4,7 +4,7 @@ This document describes the streaming extensions for cpp-httplib, providing an i
|
||||
|
||||
> **Important Notes**:
|
||||
>
|
||||
> - **No Keep-Alive**: Each `stream::Get()` call uses a dedicated connection that is closed after the response is fully read. For connection reuse, use `Client::Get()`.
|
||||
> - **No Keep-Alive**: Each `stream::Get()` call uses a dedicated connection that is closed when the returned `stream::Result` is destroyed. For connection reuse, use `Client::Get()`.
|
||||
> - **Single iteration only**: The `next()` method can only iterate through the body once.
|
||||
> - **Result is not thread-safe**: While `stream::Get()` can be called from multiple threads simultaneously, the returned `stream::Result` must be used from a single thread only.
|
||||
|
||||
@@ -114,7 +114,6 @@ The `httplib.h` header provides a more ergonomic iterator-style API.
|
||||
#include "httplib.h"
|
||||
|
||||
httplib::Client cli("http://localhost:8080");
|
||||
cli.set_follow_location(true);
|
||||
...
|
||||
|
||||
// Simple GET
|
||||
@@ -243,23 +242,29 @@ int main() {
|
||||
```cpp
|
||||
#include "httplib.h"
|
||||
|
||||
// Keeps the client and its stream alive until the response has been sent.
|
||||
struct Upstream {
|
||||
httplib::Client cli{"http://backend:8080"};
|
||||
httplib::ClientImpl::StreamHandle handle;
|
||||
};
|
||||
|
||||
httplib::Server svr;
|
||||
|
||||
svr.Get("/proxy/(.*)", [](const httplib::Request& req, httplib::Response& res) {
|
||||
httplib::Client upstream("http://backend:8080");
|
||||
auto handle = upstream.open_stream("/" + req.matches[1].str());
|
||||
|
||||
if (!handle.is_valid()) {
|
||||
auto upstream = std::make_shared<Upstream>();
|
||||
upstream->handle = upstream->cli.open_stream("GET", "/" + req.matches[1].str());
|
||||
|
||||
if (!upstream->handle.is_valid()) {
|
||||
res.status = 502;
|
||||
return;
|
||||
}
|
||||
|
||||
res.status = handle.response->status;
|
||||
|
||||
res.status = upstream->handle.response->status;
|
||||
res.set_chunked_content_provider(
|
||||
handle.response->get_header_value("Content-Type"),
|
||||
[handle = std::move(handle)](size_t, httplib::DataSink& sink) mutable {
|
||||
upstream->handle.response->get_header_value("Content-Type"),
|
||||
[upstream](size_t, httplib::DataSink& sink) {
|
||||
char buf[8192];
|
||||
auto n = handle.read(buf, sizeof(buf));
|
||||
auto n = upstream->handle.read(buf, sizeof(buf));
|
||||
if (n > 0) {
|
||||
sink.write(buf, static_cast<size_t>(n));
|
||||
return true;
|
||||
|
||||
+5
-6
@@ -119,7 +119,7 @@ using SubProtocolSelector =
|
||||
std::function<std::string(const std::vector<std::string> &protocols)>;
|
||||
```
|
||||
|
||||
The `SubProtocolSelector` receives the list of subprotocols proposed by the client (from the `Sec-WebSocket-Protocol` header) and returns the selected one. Return an empty string to decline all proposed subprotocols.
|
||||
The `SubProtocolSelector` receives the list of subprotocols proposed by the client (from the `Sec-WebSocket-Protocol` header) and returns the selected one. Return an empty string to decline all proposed subprotocols. A returned value that the client did not propose is ignored.
|
||||
|
||||
### WebSocket (Server-side)
|
||||
|
||||
@@ -151,9 +151,8 @@ bool is_open() const;
|
||||
explicit WebSocketClient(const std::string &scheme_host_port_path,
|
||||
const Headers &headers = {});
|
||||
|
||||
// Constructor with a client certificate for mutual TLS (wss:// only,
|
||||
// requires CPPHTTPLIB_OPENSSL_SUPPORT). The certificate is ignored for
|
||||
// ws:// URLs.
|
||||
// Constructor with a client certificate for mutual TLS (wss:// only, SSL
|
||||
// builds only). The certificate is ignored for ws:// URLs.
|
||||
struct PemMemory {
|
||||
const char *cert_pem;
|
||||
size_t cert_pem_len;
|
||||
@@ -199,7 +198,7 @@ void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
|
||||
template <class Rep, class Period>
|
||||
void set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
|
||||
|
||||
// SSL configuration (wss:// only, requires CPPHTTPLIB_OPENSSL_SUPPORT)
|
||||
// SSL configuration (wss:// only, SSL builds only)
|
||||
void set_ca_cert_path(const std::string &ca_cert_file_path,
|
||||
const std::string &ca_cert_dir_path = std::string());
|
||||
void set_ca_cert_store(tls::ca_store_t store);
|
||||
@@ -473,7 +472,7 @@ ws.set_websocket_max_missed_pongs(2); // close after 2 consecutive unacked pings
|
||||
|
||||
The server side has the same `set_websocket_max_missed_pongs()`.
|
||||
|
||||
With the default ping interval of 30 seconds, `max_missed_pongs = 2` detects a dead peer within ~60 seconds. The counter is reset every time a Pong frame is received, so the mechanism only works when your code is actively calling `read()` — exactly the pattern a normal WebSocket client already uses.
|
||||
With the default ping interval of 30 seconds, `max_missed_pongs = 2` detects a dead peer 60 to 90 seconds after it stops answering: the count is checked once per interval, just before the next ping goes out. A `read()` waiting on the peer at that moment returns `Fail`. The counter is reset every time a Pong frame is received, so the mechanism only works when your code is actively calling `read()`, which is exactly the pattern a normal WebSocket client already uses.
|
||||
|
||||
**The default is `0`**, which means "never close the connection because of missing pongs." Pings are still sent on the heartbeat interval, but their responses are not checked. On the server side a dead connection still does not linger: while a handler is inside `read()`, `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` (default **300 seconds = 5 minutes**) acts as a backstop. A client has no such backstop — it waits forever unless you set a read timeout — so there `max_missed_pongs` is what notices an unresponsive peer at all. On either side it is also the knob for noticing one *faster* than the 5-minute fallback.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ Learn more in the [official documentation](https://yhirose.github.io/cpp-httplib
|
||||
httplib::Server svr;
|
||||
|
||||
// HTTPS
|
||||
httplib::SSLServer svr;
|
||||
httplib::SSLServer svr("./cert.pem", "./key.pem");
|
||||
|
||||
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
|
||||
res.set_content("Hello World!", "text/plain");
|
||||
@@ -71,7 +71,7 @@ cpp-httplib supports multiple TLS backends through an abstraction layer:
|
||||
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
|
||||
|
||||
> [!NOTE]
|
||||
> **Mbed TLS / wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
|
||||
> **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
|
||||
|
||||
> [!NOTE]
|
||||
> **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. Two known behavioral differences vs OpenSSL: (1) BoringSSL's public headers require C++14 or later, so consumers must compile accordingly; (2) hostname verification is SAN-only per RFC 6125 §6.4.4 (no CN fallback).
|
||||
@@ -86,7 +86,7 @@ httplib::SSLServer svr("./cert.pem", "./key.pem");
|
||||
|
||||
// Client
|
||||
httplib::Client cli("https://localhost:1234"); // scheme + host
|
||||
httplib::SSLClient cli("localhost:1234"); // host
|
||||
httplib::SSLClient cli("localhost"); // host (port 443)
|
||||
httplib::SSLClient cli("localhost", 1234); // host, port
|
||||
|
||||
// Use your CA bundle
|
||||
@@ -103,8 +103,8 @@ cli.enable_server_hostname_verification(false);
|
||||
|
||||
When SSL operations fail, cpp-httplib provides detailed error information through `ssl_error()` and `ssl_backend_error()`:
|
||||
|
||||
- `ssl_error()` - Returns the TLS-level error code (e.g., `SSL_ERROR_SSL` for OpenSSL)
|
||||
- `ssl_backend_error()` - Returns the backend-specific error code (e.g., `ERR_get_error()` for OpenSSL/wolfSSL, return value for Mbed TLS)
|
||||
- `ssl_error()` - Returns the TLS-level error as a backend-independent `httplib::tls::ErrorCode` value (e.g., `Fatal`, `CertVerifyFailed`), cast to `int`
|
||||
- `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
|
||||
|
||||
```c++
|
||||
#define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT
|
||||
@@ -230,7 +230,7 @@ cpp-httplib automatically integrates with the OS certificate store on macOS and
|
||||
| Platform | Behavior | Disable (compile time) |
|
||||
| :------- | :------- | :--------------------- |
|
||||
| macOS | Loads system certs from Keychain (link `CoreFoundation` and `Security` with `-framework`). Requires Apple Clang; GCC is not supported for this feature. | `CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES` |
|
||||
| Windows | Verifies certs via CryptoAPI (`CertGetCertificateChain` / `CertVerifyCertificateChainPolicy`) with revocation checking | `CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE` |
|
||||
| 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, verification can also be disabled at runtime:
|
||||
|
||||
@@ -337,7 +337,7 @@ 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 the dedicated methods above instead.
|
||||
* 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 and WebSocket upgrades remain `GET`/`HEAD` only.
|
||||
* 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.
|
||||
|
||||
### Bind a socket to multiple interfaces and any available port
|
||||
@@ -452,6 +452,9 @@ svr.set_logger([](const httplib::Request& req, const httplib::Response& res) {
|
||||
});
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `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](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:
|
||||
@@ -515,7 +518,7 @@ svr.set_exception_handler([](const auto& req, auto& res, std::exception_ptr ep)
|
||||
```
|
||||
|
||||
> [!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!
|
||||
> 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
|
||||
|
||||
@@ -566,21 +569,21 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
|
||||
Request received
|
||||
│
|
||||
├─ expect_100_continue_handler (when the request has "Expect: 100-continue")
|
||||
│ └─ returns a status other than 100 → stop here
|
||||
│ └─ returns a status other than 100 → go straight to post_routing_handler
|
||||
│
|
||||
├─ pre_routing_handler route not matched yet, body not read
|
||||
│ └─ returns Handled → stop here
|
||||
│ └─ returns Handled → go straight to post_routing_handler
|
||||
│
|
||||
├─ file_request_handler (GET/HEAD, static file serving)
|
||||
├─ file_request_handler when a static file is served (GET only)
|
||||
│
|
||||
├─ route matching → req.matched_route is set
|
||||
│
|
||||
├─ pre_request_handler route matched, body NOT read yet
|
||||
│ └─ returns Handled → stop here (route handler is skipped)
|
||||
│ └─ returns Handled → go straight to post_routing_handler
|
||||
│
|
||||
├─ route handler Get/Post/...; the request body is read first
|
||||
│
|
||||
└─ post_routing_handler after routing completes
|
||||
└─ post_routing_handler just before the response is written
|
||||
|
||||
On a thrown exception → exception_handler
|
||||
On an error status (4xx/5xx) → error_handler
|
||||
@@ -608,7 +611,7 @@ svr.set_pre_routing_handler([](const auto& req, auto& res) {
|
||||
return Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
|
||||
svr.Get("/me", [](const auto& /*req*/, auto& res) {
|
||||
svr.Get("/me", [](const Request& /*req*/, Response& res) {
|
||||
auto* ctx = res.user_data.get<AuthContext>("auth");
|
||||
if (!ctx) {
|
||||
res.status = StatusCode::Unauthorized_401;
|
||||
@@ -905,7 +908,7 @@ Please see [Server example](https://github.com/yhirose/cpp-httplib/blob/master/e
|
||||
|
||||
`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 all threads are busy and a new task arrives, a temporary thread is spawned (up to the maximum). When a dynamic thread finishes its task and the queue is empty, or after an idle timeout, it exits automatically. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`.
|
||||
When all threads are busy and a new task arrives, 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`.
|
||||
|
||||
If you want to set the thread counts at runtime:
|
||||
|
||||
@@ -1039,6 +1042,8 @@ enum class Error {
|
||||
HTTPParsing,
|
||||
InvalidRangeHeader,
|
||||
UnsupportedContentEncoding,
|
||||
WebSocketHandshake,
|
||||
UserCallbackException,
|
||||
};
|
||||
```
|
||||
|
||||
@@ -1254,7 +1259,7 @@ std::string body = ...;
|
||||
|
||||
auto res = cli.Post(
|
||||
"/stream", body.size(),
|
||||
[](size_t offset, size_t length, DataSink &sink) {
|
||||
[&](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.
|
||||
},
|
||||
@@ -1307,7 +1312,7 @@ cli.set_bearer_token_auth("token");
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> OpenSSL is required for Digest Authentication.
|
||||
> A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
|
||||
|
||||
### Proxy server support
|
||||
|
||||
@@ -1325,12 +1330,12 @@ cli.set_proxy_bearer_token_auth("pass");
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> OpenSSL is required for Digest Authentication.
|
||||
> A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
|
||||
|
||||
#### Bypass the proxy for specific hosts (`NO_PROXY`)
|
||||
|
||||
```cpp
|
||||
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
|
||||
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.
|
||||
@@ -1475,8 +1480,8 @@ for (auto it = req.headers.equal_range("Accept-Encoding").first;
|
||||
std::cout << it->second << std::endl;
|
||||
}
|
||||
|
||||
// get_header_value(key, id) reaches a specific one directly.
|
||||
auto second = req.get_header_value("Accept-Encoding", 1); // "br"
|
||||
// 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.
|
||||
@@ -1486,7 +1491,7 @@ auto second = req.get_header_value("Accept-Encoding", 1); // "br"
|
||||
|
||||
## 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.
|
||||
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.
|
||||
|
||||
## Compression
|
||||
|
||||
@@ -1495,10 +1500,15 @@ The server can apply compression to the following MIME type contents:
|
||||
- all text types except text/event-stream
|
||||
- image/svg+xml
|
||||
- application/javascript
|
||||
- application/x-javascript
|
||||
- application/json
|
||||
- application/ld+json
|
||||
- application/xml
|
||||
- application/protobuf
|
||||
- application/xhtml+xml
|
||||
- application/rss+xml
|
||||
- application/atom+xml
|
||||
- application/xslt+xml
|
||||
- application/protobuf
|
||||
|
||||
A response that already carries `Content-Encoding` is sent as it is. A handler serving content it encoded itself, an asset compressed at build time for instance, keeps its own coding and its own bytes:
|
||||
|
||||
@@ -1635,7 +1645,6 @@ Process large responses without loading everything into memory.
|
||||
|
||||
```c++
|
||||
httplib::Client cli("localhost", 8080);
|
||||
cli.set_follow_location(true);
|
||||
...
|
||||
|
||||
auto result = httplib::stream::Get(cli, "/large-file");
|
||||
@@ -1715,7 +1724,7 @@ SSL is also supported via `wss://` scheme (e.g. `WebSocketClient("wss://example.
|
||||
|
||||
> **WebSocket extensions are not supported.** `permessage-deflate` and other RFC 6455 extensions are not implemented. If a client proposes them via `Sec-WebSocket-Extensions`, the server silently declines them in its handshake response.
|
||||
|
||||
> **Unresponsive-peer detection.** Heartbeat pings also serve as a liveness probe when `set_websocket_max_missed_pongs(n)` is set: if the client sends `n` consecutive pings without receiving a pong, it will close the connection. Disabled by default (`0`).
|
||||
> **Unresponsive-peer detection.** Heartbeat pings also serve as a liveness probe when `set_websocket_max_missed_pongs(n)` is set: once `n` consecutive pings have gone unanswered, the connection is closed and a `read()` waiting on it fails. Both `WebSocketClient` and `Server` have the setter. Disabled by default (`0`).
|
||||
|
||||
See [README-websocket.md](README-websocket.md) for more details.
|
||||
|
||||
@@ -1724,12 +1733,14 @@ See [README-websocket.md](README-websocket.md) for more details.
|
||||
`set_socket_opt` is a convenience wrapper around `setsockopt` for setting integer socket options:
|
||||
|
||||
```cpp
|
||||
auto sock = svr.socket();
|
||||
httplib::set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
|
||||
svr.set_socket_options([](socket_t sock) {
|
||||
httplib::default_socket_options(sock);
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
|
||||
});
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> For most use cases, prefer `set_tcp_nodelay(true)` or `set_socket_options(callback)` on the Server/Client instead of calling `set_socket_opt` directly.
|
||||
> `set_socket_options` replaces the default socket options, so call `default_socket_options()` in the callback to keep them. For `TCP_NODELAY`, `set_tcp_nodelay(true)` is simpler.
|
||||
|
||||
## Split httplib.h into .h and .cc
|
||||
|
||||
@@ -1758,7 +1769,9 @@ Dockerfile for static HTTP server is available. Port number of this HTTP server
|
||||
...
|
||||
|
||||
> docker run --rm -it -p 8080:80 -v ./docker/html:/html cpp-httplib-server
|
||||
Serving HTTP on 0.0.0.0 port 80 ...
|
||||
Serving HTTP on 0.0.0.0:80
|
||||
Mount point: / -> ./html
|
||||
Press Ctrl+C to shutdown gracefully...
|
||||
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 ..."
|
||||
@@ -1768,7 +1781,9 @@ From Docker Hub
|
||||
|
||||
```bash
|
||||
> docker run --rm -it -p 8080:80 -v ./docker/html:/html yhirose4dockerhub/cpp-httplib-server
|
||||
Serving HTTP on 0.0.0.0 port 80 ...
|
||||
Serving HTTP on 0.0.0.0:80
|
||||
Mount point: / -> ./html
|
||||
Press Ctrl+C to shutdown gracefully...
|
||||
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 ..."
|
||||
@@ -1780,19 +1795,13 @@ 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.
|
||||
>
|
||||
> `std::regex` implementations can overflow the stack while matching a long input, even with a pattern as simple as `.*`. To keep a request from triggering this, a regex route is never applied to a path longer than `CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH` (256 by default); such a path does not match the route. Raising the limit brings the risk back with it.
|
||||
>
|
||||
> Path parameters are matched without `std::regex` and have no such limit, so prefer them where they fit:
|
||||
>
|
||||
> ```cpp
|
||||
> // This pattern can cause stack overflow with large input
|
||||
> svr.Get(".*", handler);
|
||||
> ```
|
||||
>
|
||||
> Consider using simpler patterns or path parameters to avoid this issue:
|
||||
>
|
||||
> ```cpp
|
||||
> // Safer alternatives
|
||||
> svr.Get("/users/:id", handler); // Path parameters
|
||||
> svr.Get(R"(/api/v\d+/.*)", handler); // More specific patterns
|
||||
> svr.Get(R"(/api/v\d+/.*)", handler); // Regex route, limited to short paths
|
||||
> ```
|
||||
|
||||
### g++
|
||||
|
||||
+29
-7
@@ -48,6 +48,23 @@ std::string get_error_time_format() {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// Escape a value for a log line the way NGINX does: '"', '\\', control
|
||||
// bytes and non-ASCII bytes become \xHH. Request fields are attacker-controlled
|
||||
// (e.g. a raw CR in the request target or a decoded %0D%0A in req.path), so
|
||||
// writing them verbatim would let a client forge extra log lines.
|
||||
std::string escape_log(const std::string &s) {
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (unsigned char c : s) {
|
||||
if (c == '"' || c == '\\' || c < 0x20 || c >= 0x7f) {
|
||||
out += std::format("\\x{:02X}", c);
|
||||
} else {
|
||||
out += static_cast<char>(c);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// NGINX Combined log format:
|
||||
// $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent
|
||||
// "$http_referer" "$http_user_agent"
|
||||
@@ -55,18 +72,22 @@ void nginx_access_logger(const Request &req, const Response &res) {
|
||||
std::string remote_user =
|
||||
"-"; // cpp-httplib doesn't have built-in auth user tracking
|
||||
auto time_local = get_time_format();
|
||||
auto request = std::format("{} {} {}", req.method, req.path, req.version);
|
||||
// $request is the original request line, so log the raw target rather than
|
||||
// the percent-decoded req.path.
|
||||
auto request = std::format("{} {} {}", req.method, req.target, req.version);
|
||||
auto status = res.status;
|
||||
auto body_bytes_sent = res.body.size();
|
||||
// A static file is sent by a content provider, which leaves res.body empty.
|
||||
auto body_bytes_sent =
|
||||
req.method == "HEAD" ? 0 : res.get_header_value_u64("Content-Length");
|
||||
auto http_referer = req.get_header_value("Referer");
|
||||
if (http_referer.empty()) http_referer = "-";
|
||||
auto http_user_agent = req.get_header_value("User-Agent");
|
||||
if (http_user_agent.empty()) http_user_agent = "-";
|
||||
|
||||
std::cout << std::format("{} - {} [{}] \"{}\" {} {} \"{}\" \"{}\"",
|
||||
req.remote_addr, remote_user, time_local, request,
|
||||
status, body_bytes_sent, http_referer,
|
||||
http_user_agent)
|
||||
req.remote_addr, remote_user, time_local,
|
||||
escape_log(request), status, body_bytes_sent,
|
||||
escape_log(http_referer), escape_log(http_user_agent))
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
@@ -79,14 +100,15 @@ void nginx_error_logger(const Error &err, const Request *req) {
|
||||
|
||||
if (req) {
|
||||
auto request =
|
||||
std::format("{} {} {}", req->method, req->path, req->version);
|
||||
std::format("{} {} {}", req->method, req->target, req->version);
|
||||
auto host = req->get_header_value("Host");
|
||||
if (host.empty()) host = "-";
|
||||
|
||||
std::cerr << std::format("{} [{}] {}, client: {}, request: "
|
||||
"\"{}\", host: \"{}\"",
|
||||
time_local, level, to_string(err),
|
||||
req->remote_addr, request, host)
|
||||
req->remote_addr, escape_log(request),
|
||||
escape_log(host))
|
||||
<< std::endl;
|
||||
} else {
|
||||
// If no request context, just log the error
|
||||
|
||||
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
|
||||
|
||||
[site]
|
||||
title = "cpp-httplib"
|
||||
version = "0.57.1"
|
||||
version = "0.61.0"
|
||||
hostname = "https://yhirose.github.io"
|
||||
base_path = "/cpp-httplib"
|
||||
footer_message = "© 2026 Yuji Hirose. All rights reserved."
|
||||
|
||||
@@ -17,7 +17,7 @@ auto res = cli.Post("/api/users", j.dump(), "application/json");
|
||||
|
||||
Pass the JSON string as the second argument to `Post()` and the Content-Type as the third. The same pattern works with `Put()` and `Patch()`.
|
||||
|
||||
> **Warning:** If you omit the Content-Type (the third argument), the server may not recognize the body as JSON. Always specify `"application/json"`.
|
||||
> **Warning:** If the Content-Type (the third argument) is anything other than `"application/json"`, the server may not recognize the body as JSON. Always specify `"application/json"`.
|
||||
|
||||
## Receive a JSON response
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ auto res = cli.Get("/large-file",
|
||||
std::cout << std::endl;
|
||||
```
|
||||
|
||||
The callback fires each time data arrives. `total` comes from the Content-Length header — if the server doesn't send one, it may be `0`. In that case, you can't compute a percentage, so just display bytes received.
|
||||
The callback fires each time data arrives. `total` comes from the Content-Length header. For a response without one (chunked transfer, for example), the progress callback is not called at all.
|
||||
|
||||
## Upload progress
|
||||
|
||||
@@ -54,6 +54,8 @@ auto res = cli.Get("/large-file",
|
||||
});
|
||||
```
|
||||
|
||||
> **Note:** A response without Content-Length never calls the progress callback, so it cannot be cancelled this way. Return `false` from a `ContentReceiver` instead.
|
||||
|
||||
> **Note:** `ContentReceiver` and the progress callback can be used together. When you want to stream to a file and show progress at the same time, pass both.
|
||||
|
||||
> For a concrete example of saving to a file, see [C01. Get the response body / save to a file](../c01-get-response-body).
|
||||
@@ -16,7 +16,7 @@ cli.set_max_timeout(5000); // 5 seconds (in milliseconds)
|
||||
auto res = cli.Get("/slow-endpoint");
|
||||
```
|
||||
|
||||
The value is in milliseconds. Connection, send, and receive together — the whole request is aborted if it exceeds the limit.
|
||||
The value is in milliseconds. Once that much time has passed since the request started, waiting for the response is cut off. The limit does not shorten the connection and write waits themselves, so bound those with `set_connection_timeout` and `set_write_timeout`.
|
||||
|
||||
## Use `std::chrono`
|
||||
|
||||
|
||||
@@ -4,30 +4,29 @@ order: 14
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
When you send multiple requests through the same `httplib::Client` instance, the TCP connection is reused automatically. HTTP/1.1 Keep-Alive does the work for you — you don't pay the TCP and TLS handshake cost on every call.
|
||||
By default, `httplib::Client` closes the connection after every request (it sends `Connection: close`). Call `set_keep_alive(true)` and the requests you send through the same instance share one TCP connection, so you don't pay the TCP and TLS handshake cost on every call.
|
||||
|
||||
## Connections are reused automatically
|
||||
## Enable Keep-Alive
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("https://api.example.com");
|
||||
cli.set_keep_alive(true);
|
||||
|
||||
auto res1 = cli.Get("/users/1");
|
||||
auto res2 = cli.Get("/users/2"); // reuses the same connection
|
||||
auto res3 = cli.Get("/users/3"); // reuses the same connection
|
||||
```
|
||||
|
||||
No special config required. Just hold on to `cli` — internally, the socket stays open across calls. The effect is especially noticeable over HTTPS, where the TLS handshake is expensive.
|
||||
After that, just hold on to `cli`. Internally, the socket stays open across calls. The effect is especially noticeable over HTTPS, where the TLS handshake is expensive.
|
||||
|
||||
## Disable Keep-Alive explicitly
|
||||
## Turn Keep-Alive back off
|
||||
|
||||
To force a fresh connection every time, call `set_keep_alive(false)`. Mostly useful for testing.
|
||||
To go back to a fresh connection every time, call `set_keep_alive(false)`. This is the default behavior.
|
||||
|
||||
```cpp
|
||||
cli.set_keep_alive(false);
|
||||
```
|
||||
|
||||
For normal use, leave it on (the default).
|
||||
|
||||
## Don't create a `Client` per request
|
||||
|
||||
If you create a `Client` inside a loop and let it fall out of scope each iteration, you lose the reuse benefit. Create the instance outside the loop.
|
||||
@@ -36,11 +35,13 @@ If you create a `Client` inside a loop and let it fall out of scope each iterati
|
||||
// Bad: a new connection every iteration
|
||||
for (auto id : ids) {
|
||||
httplib::Client cli("https://api.example.com");
|
||||
cli.set_keep_alive(true);
|
||||
cli.Get("/users/" + id);
|
||||
}
|
||||
|
||||
// Good: the connection is reused
|
||||
httplib::Client cli("https://api.example.com");
|
||||
cli.set_keep_alive(true);
|
||||
for (auto id : ids) {
|
||||
cli.Get("/users/" + id);
|
||||
}
|
||||
@@ -50,4 +51,4 @@ for (auto id : ids) {
|
||||
|
||||
If you want to send requests in parallel from multiple threads, give each thread its own `Client` instance. A single `Client` uses a single TCP connection, so firing concurrent requests at the same instance ends up serializing them anyway.
|
||||
|
||||
> **Note:** If the server closes the connection after its Keep-Alive timeout, cpp-httplib reconnects and retries transparently. You don't need to handle this in application code.
|
||||
> **Note:** If the server closes the connection after its Keep-Alive timeout, cpp-httplib notices before it sends the next request and reconnects. You don't need to handle this in application code.
|
||||
@@ -4,7 +4,7 @@ order: 15
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
cpp-httplib supports compression when sending and decompression when receiving. You just need to build it with zlib or Brotli enabled.
|
||||
cpp-httplib supports compression when sending and decompression when receiving. You just need to build it with zlib, Brotli, or Zstd enabled.
|
||||
|
||||
## Build-time setup
|
||||
|
||||
@@ -13,10 +13,11 @@ To use compression, define these macros before including `httplib.h`:
|
||||
```cpp
|
||||
#define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate
|
||||
#define CPPHTTPLIB_BROTLI_SUPPORT // brotli
|
||||
#define CPPHTTPLIB_ZSTD_SUPPORT // zstd
|
||||
#include <httplib.h>
|
||||
```
|
||||
|
||||
You'll also need to link against `zlib` or `brotli`.
|
||||
You'll also need to link against `zlib`, `brotli`, or `zstd`, whichever you enabled.
|
||||
|
||||
## Compress the request body
|
||||
|
||||
@@ -28,7 +29,7 @@ std::string big_payload = build_payload();
|
||||
auto res = cli.Post("/api/data", big_payload, "application/json");
|
||||
```
|
||||
|
||||
With `set_compress(true)`, the body of POST or PUT requests gets gzipped before sending. The server needs to handle compressed bodies too.
|
||||
With `set_compress(true)`, the body of POST or PUT requests is compressed before sending. The encoding is the first one enabled in your build, in the order Brotli, gzip, Zstd. The server needs to handle compressed bodies too.
|
||||
|
||||
## Decompress the response
|
||||
|
||||
@@ -44,4 +45,4 @@ With `set_decompress(true)`, the client automatically decompresses responses tha
|
||||
|
||||
It's on by default, so normally you don't need to do anything. Set it to `false` only if you want the raw compressed bytes.
|
||||
|
||||
> **Warning:** If you build without `CPPHTTPLIB_ZLIB_SUPPORT`, calling `set_compress()` or `set_decompress()` does nothing. If compression isn't working, check the macro definition first.
|
||||
> **Warning:** If you build without any compression library, `set_compress(true)` leaves the request uncompressed. And a response compressed with an encoding your build lacks makes the request fail with `Error::UnsupportedContentEncoding`. If compression isn't working, check the macro definitions first.
|
||||
@@ -55,7 +55,7 @@ You often want internal endpoints to skip the proxy. Configure a bypass list wit
|
||||
|
||||
```cpp
|
||||
cli.set_proxy("proxy.internal", 8080);
|
||||
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
|
||||
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
|
||||
```
|
||||
|
||||
Each entry is one of:
|
||||
|
||||
@@ -29,8 +29,8 @@ Use `if (res)` to check success. On failure, `res.error()` returns a `httplib::E
|
||||
| --- | --- |
|
||||
| `Error::Connection` | Couldn't connect to the server |
|
||||
| `Error::ConnectionTimeout` | Connection timeout (`set_connection_timeout`) |
|
||||
| `Error::Read` / `Error::Write` | Error during send or receive |
|
||||
| `Error::Timeout` | Overall timeout set via `set_max_timeout` |
|
||||
| `Error::Read` / `Error::Write` | Error during send or receive. A timeout from `set_read_timeout` or `set_max_timeout` is also reported as `Error::Read` |
|
||||
| `Error::Timeout` | A body read timed out in `stream::Get()` or `SSEClient` |
|
||||
| `Error::ExceedRedirectCount` | Too many redirects |
|
||||
| `Error::SSLConnection` | TLS handshake failed |
|
||||
| `Error::SSLServerVerification` | Server certificate verification failed |
|
||||
|
||||
@@ -24,19 +24,24 @@ if (!res) {
|
||||
}
|
||||
```
|
||||
|
||||
`ssl_error()` returns the error code from the SSL library (e.g., OpenSSL's `SSL_get_error()`). `ssl_backend_error()` gives you the backend's more detailed error value — for OpenSSL, that's `ERR_get_error()`.
|
||||
`ssl_error()` is a backend-independent TLS error category: an `httplib::tls::ErrorCode` cast to `int`. `ssl_backend_error()` gives you the backend's own error value. With OpenSSL that is `ERR_get_error()` when the handshake failed, and the verify result (`X509_V_ERR_*`) when certificate verification failed.
|
||||
|
||||
## Format OpenSSL errors as strings
|
||||
|
||||
When you have a value from `ssl_backend_error()`, pass it to OpenSSL's `ERR_error_string()` to get a readable message.
|
||||
When you have a value from `ssl_backend_error()`, pass it to the OpenSSL function that matches the kind of failure to get a readable message.
|
||||
|
||||
```cpp
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/x509.h>
|
||||
|
||||
if (res.ssl_backend_error() != 0) {
|
||||
if (res.error() == httplib::Error::SSLConnection) {
|
||||
char buf[256];
|
||||
ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf));
|
||||
std::cerr << "openssl: " << buf << std::endl;
|
||||
} else if (res.error() == httplib::Error::SSLServerVerification ||
|
||||
res.error() == httplib::Error::SSLServerHostnameVerification) {
|
||||
auto code = static_cast<long>(res.ssl_backend_error());
|
||||
std::cerr << "openssl: " << X509_verify_cert_error_string(code) << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ sse.on_event("leave", [](const auto &msg) {
|
||||
});
|
||||
```
|
||||
|
||||
`on_message()` serves as a generic fallback for unnamed events (the default `message` type).
|
||||
`on_message()` is the generic fallback: it receives every event that has no handler registered through `on_event()`. With `on_event("message", ...)` registered as above, `message` events go there instead.
|
||||
|
||||
## Connection lifecycle and errors
|
||||
|
||||
@@ -55,7 +55,7 @@ sse.on_error([](httplib::Error err) {
|
||||
});
|
||||
```
|
||||
|
||||
Hook into connection open and error events. Even when the error handler fires, `SSEClient` keeps trying to reconnect in the background.
|
||||
Hook into connection open and error events. Even when the error handler fires, `SSEClient` keeps trying to reconnect in the background. The exceptions are a 204, 403, or 404 response, after which it stops.
|
||||
|
||||
## Run asynchronously
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ You can even mount multiple directories at the same path — they're searched in
|
||||
|
||||
## Combine with API handlers
|
||||
|
||||
Static files and API handlers coexist happily. Handlers registered with `Get()` and friends take priority; the mount points are searched only when nothing matches.
|
||||
Static files and API handlers coexist happily. For GET and HEAD, the mount points are searched first; handlers registered with `Get()` and friends run only when no file is found.
|
||||
|
||||
```cpp
|
||||
svr.Get("/api/users", [](const auto &req, auto &res) {
|
||||
|
||||
@@ -15,14 +15,15 @@ svr.Get("/download", [](const httplib::Request &req, httplib::Response &res) {
|
||||
res.set_content_provider(
|
||||
total_size, "application/octet-stream",
|
||||
[](size_t offset, size_t length, httplib::DataSink &sink) {
|
||||
auto data = read_range_from_file("large.bin", offset, length);
|
||||
auto n = std::min(length, size_t(64 * 1024));
|
||||
auto data = read_range_from_file("large.bin", offset, n);
|
||||
sink.write(data.data(), data.size());
|
||||
return true;
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The lambda is called repeatedly with `offset` and `length`. Read just that range and write it to `sink`. Only a small chunk sits in memory at any given time.
|
||||
The lambda is called repeatedly with `offset`, the position sent so far, and `length`, the number of bytes still to send. Cap how much you read per call and write it to `sink`, and only a small chunk sits in memory at any given time.
|
||||
|
||||
## Just send a file
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ svr.Post("/upload",
|
||||
});
|
||||
```
|
||||
|
||||
When `content_reader` returns `false`, set the response status yourself. The rest of the body is left unread and the connection is closed, so a client that is still sending sees the connection drop.
|
||||
When `content_reader` returns `false`, the response status becomes 400 (413 if the body exceeded the size limit). Set it yourself if you want a different one. The rest of the body is left unread and the connection is closed, so a client that is still sending sees the connection drop.
|
||||
|
||||
> **Warning:** When you use `HandlerWithContentReader`, `req.body` stays **empty**. Handle the body yourself inside the callbacks.
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ That's it. If the client sent `Accept-Encoding: gzip`, cpp-httplib compresses th
|
||||
|
||||
## Encoding priority
|
||||
|
||||
When the client accepts multiple encodings, cpp-httplib picks in this order (among those enabled at build time): Brotli → Zstd → gzip. Your code doesn't need to care — you always get the most efficient option available.
|
||||
When the client accepts multiple encodings, cpp-httplib picks the one with the highest q-value in `Accept-Encoding`. On a tie the order is Brotli → gzip → Zstd (among those enabled at build time).
|
||||
|
||||
## Streaming responses are compressed too
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
|
||||
|
||||
## Typical value types
|
||||
|
||||
Strings, numbers, structs, `std::shared_ptr` — anything copyable or movable works.
|
||||
Strings, numbers, structs, `std::shared_ptr`: anything copyable works.
|
||||
|
||||
```cpp
|
||||
res.user_data.set("user_id", std::string{"42"});
|
||||
|
||||
@@ -48,7 +48,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
||||
auto *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
|
||||
auto elapsed = start
|
||||
? std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
|
||||
@@ -52,6 +52,6 @@ int main() {
|
||||
|
||||
## What happens to in-flight requests
|
||||
|
||||
When you call `stop()`, new connections are refused, but requests already being processed are **allowed to finish**. Once all workers drain, `listen()` returns. That's what makes it graceful.
|
||||
When you call `stop()`, new connections are refused, but handlers that are already running are **allowed to finish**. A response still being sent by a content provider (a streaming response, for example) is cut short, though. Once all workers drain, `listen()` returns. That's what makes it graceful.
|
||||
|
||||
> **Warning:** There's a wait between calling `stop()` and `listen()` returning — it's the time in-flight requests take to finish. To enforce a timeout, you'll need to add your own shutdown timer in application code.
|
||||
@@ -19,7 +19,7 @@ svr.Get("/", [](const auto &, auto &res) {
|
||||
svr.listen("/tmp/httplib.sock", 80);
|
||||
```
|
||||
|
||||
Call `set_address_family(AF_UNIX)` first, then pass the socket file path as the first argument to `listen()`. The port number is unused but required by the signature — pass any value.
|
||||
Call `set_address_family(AF_UNIX)` first, then pass the socket file path as the first argument to `listen()`. The port number is unused but required by the signature. Pass any value other than `0`, which makes `listen()` fail.
|
||||
|
||||
## Client side
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ httplib::SSLClient cli("api.example.com", 443,
|
||||
auto res = cli.Get("/");
|
||||
```
|
||||
|
||||
Note you're using `SSLClient` directly, not `Client`. If the private key has a password, pass it as the fifth argument.
|
||||
If the certificate and key paths are all you need, `Client` takes them too: `httplib::Client cli("https://api.example.com", "client-cert.pem", "client-key.pem")`. When the private key has a password, use `SSLClient` and pass it as the fifth argument.
|
||||
|
||||
The client side has the same `PemMemory` struct too, letting you set the client certificate from PEM in memory.
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ cli.set_websocket_max_missed_pongs(2); // close after 2 consecutive unacked ping
|
||||
|
||||
The server side has the same `set_websocket_max_missed_pongs()`.
|
||||
|
||||
With a 30-second ping interval and `max_missed_pongs = 2`, a dead peer is detected within roughly 60 seconds and the connection is closed with `CloseStatus::GoingAway` and the reason `"pong timeout"`.
|
||||
With a 30-second ping interval and `max_missed_pongs = 2`, a dead peer is detected 60 to 90 seconds after it stops answering, and the connection is closed with `CloseStatus::GoingAway` and the reason `"pong timeout"`. A `read()` waiting on the peer at that moment returns `Fail`.
|
||||
|
||||
The counter is reset whenever `read()` consumes an incoming Pong frame, so this only works if your code is actively calling `read()` in a loop — which is what a normal WebSocket client does anyway.
|
||||
|
||||
|
||||
@@ -18,10 +18,6 @@ Simply pass the path to a model file to `llamalib::Llama`, and model loading, co
|
||||
int main() {
|
||||
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
|
||||
|
||||
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
// ... Build and start the HTTP server ...
|
||||
}
|
||||
```
|
||||
@@ -78,7 +74,7 @@ svr.Post("/translate",
|
||||
});
|
||||
```
|
||||
|
||||
`llm.chat()` can throw exceptions during inference (for example, when the context length is exceeded). By catching them with `try/catch` and returning the error as JSON, we prevent the server from crashing.
|
||||
`llm.chat()` can throw exceptions during inference (for example, when the context length is exceeded). We catch them with `try/catch` and return the error as JSON. Left uncaught, cpp-httplib would still answer with a 500, but the client would not learn the cause.
|
||||
|
||||
## 2.3 Complete Code
|
||||
|
||||
@@ -111,10 +107,6 @@ int main() {
|
||||
// Load the model downloaded in Chapter 1
|
||||
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
|
||||
|
||||
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
// Log requests and responses
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
|
||||
@@ -73,7 +73,7 @@ A few key points:
|
||||
- After writing to `sink.os`, you can check whether the client is still connected with `sink.os.good()`. If the client has disconnected, it returns `false` to stop inference
|
||||
- Each token is escaped as a JSON string using `json(token).dump()` before sending. This is safe even for tokens containing newlines or quotes
|
||||
- The first three arguments of `dump(-1, ' ', false, ...)` are the defaults. What matters is the fourth argument, `json::error_handler_t::replace`. Since the LLM returns tokens at the subword level, multi-byte characters (such as Japanese) can be split mid-character across tokens. Passing an incomplete UTF-8 byte sequence directly to `dump()` would throw an exception, so `replace` safely substitutes them. The browser reassembles the bytes on its end, so everything displays correctly
|
||||
- The entire lambda is wrapped in `try/catch`. `llm.chat()` can throw exceptions for reasons such as exceeding the context window. If an exception goes uncaught inside the lambda, the server will crash, so we return the error as an SSE event instead
|
||||
- The entire lambda is wrapped in `try/catch`. `llm.chat()` can throw exceptions for reasons such as exceeding the context window. If an exception goes uncaught inside the lambda, cpp-httplib just drops the connection and the client never learns the cause, so we return the error as an SSE event instead
|
||||
- `data: [DONE]` follows the OpenAI API convention to signal the end of the stream to the client
|
||||
|
||||
## 3.4 Complete Code
|
||||
@@ -107,10 +107,6 @@ int main() {
|
||||
// Load the GGUF model
|
||||
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
|
||||
|
||||
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
// Log requests and responses
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
|
||||
@@ -219,7 +219,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true);
|
||||
cli.set_read_timeout(std::chrono::hours(1));
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -469,7 +468,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true); // Hugging Face redirects to a CDN
|
||||
cli.set_read_timeout(std::chrono::hours(1)); // Set a long timeout for large models
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -539,10 +537,6 @@ int main() {
|
||||
auto llm = llamalib::Llama{path};
|
||||
std::mutex llm_mutex; // Protect access during model switching
|
||||
|
||||
// Set a long timeout since LLM inference takes time (default is 5 seconds)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
<< std::endl;
|
||||
|
||||
@@ -939,7 +939,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true); // Hugging Face redirects to CDN
|
||||
cli.set_read_timeout(std::chrono::hours(1)); // Long timeout for large models
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -1008,10 +1007,6 @@ int main() {
|
||||
}
|
||||
auto llm = llamalib::Llama{path};
|
||||
|
||||
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
<< std::endl;
|
||||
|
||||
@@ -407,7 +407,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true); // Hugging Face redirects to a CDN
|
||||
cli.set_read_timeout(std::chrono::hours(1)); // Long timeout for large models
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -469,10 +468,6 @@ int main() {
|
||||
auto llm = llamalib::Llama{path};
|
||||
std::mutex llm_mutex; // Protect access during model switching
|
||||
|
||||
// Set a long timeout since LLM inference takes time (default is 5 seconds)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
<< std::endl;
|
||||
|
||||
@@ -11,13 +11,17 @@ Over the course of six chapters, we built a translation desktop app from scratch
|
||||
## 7.1 Source Code Location
|
||||
|
||||
```ascii
|
||||
llama.cpp/tools/server/
|
||||
├── server.cpp # Main server implementation
|
||||
├── httplib.h # cpp-httplib (bundled version)
|
||||
└── ...
|
||||
llama.cpp/
|
||||
├── tools/server/
|
||||
│ ├── server.cpp # Entry point
|
||||
│ ├── server-http.cpp # HTTP server (the layer that uses cpp-httplib)
|
||||
│ ├── server-context.cpp # Inference and slot management
|
||||
│ └── ...
|
||||
└── vendor/cpp-httplib/
|
||||
└── httplib.h # cpp-httplib (bundled version)
|
||||
```
|
||||
|
||||
The code is contained in a single `server.cpp`. It runs to several thousand lines, but once you understand the structure, you can narrow down the parts worth reading.
|
||||
The implementation is split across several files by role. Together they run to more than 20,000 lines, but once you understand the structure, you can narrow down the parts worth reading.
|
||||
|
||||
## 7.2 OpenAI-Compatible API
|
||||
|
||||
@@ -141,7 +145,7 @@ Let's organize the differences we've covered.
|
||||
| SSE format | Tokens only | OpenAI-compatible JSON |
|
||||
| KV cache | Cleared each time | Prefix reuse |
|
||||
| Structured output | None | JSON Schema / grammar constraints |
|
||||
| Code size | ~200 lines | Several thousand lines |
|
||||
| Code size | ~200 lines | Over 20,000 lines |
|
||||
|
||||
Our code is simple because of the assumption that "one person uses it as a desktop app." If you're building a server for multiple users or one that integrates with the existing ecosystem, `llama-server`'s design serves as a valuable reference.
|
||||
|
||||
|
||||
@@ -200,8 +200,8 @@ auto res = cli.Post("/submit", httplib::Params{
|
||||
});
|
||||
if (res) {
|
||||
std::cout << res->body << std::endl;
|
||||
// age = 30
|
||||
// name = Alice
|
||||
// age = 30
|
||||
}
|
||||
```
|
||||
|
||||
@@ -241,7 +241,7 @@ auto res = cli.Get("/hi");
|
||||
if (!res) {
|
||||
// Connection error
|
||||
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
|
||||
// Error: Connection
|
||||
// Error: Could not establish connection
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ svr.set_mount_point("/", "./public");
|
||||
svr.listen("0.0.0.0", 8080);
|
||||
```
|
||||
|
||||
Handlers take priority. The handler responds to `/api/hello`. For every other path, the server looks for a file in `./public`.
|
||||
The server looks for a file in `./public` first and calls the handler when there is none. So the handler responds to `/api/hello` unless you put a file at `./public/api/hello`.
|
||||
|
||||
## Adding response headers
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ svr.Get("/stream", [](const auto &, auto &res) {
|
||||
res.set_chunked_content_provider("text/plain",
|
||||
[](size_t offset, httplib::DataSink &sink) {
|
||||
sink.write("chunk\n", 6);
|
||||
return true; // Return false to finish
|
||||
return true; // Call sink.done() to finish
|
||||
});
|
||||
});
|
||||
```
|
||||
@@ -155,7 +155,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
});
|
||||
|
||||
svr.set_post_routing_handler([](const auto &req, auto &res) {
|
||||
// Runs after the response is sent
|
||||
// Runs just before the response is sent
|
||||
res.set_header("X-Server", "cpp-httplib");
|
||||
});
|
||||
```
|
||||
@@ -168,7 +168,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
|
||||
svr.Get("/me", [](const auto &req, auto &res) {
|
||||
svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
|
||||
auto *user = res.user_data.get<std::string>("auth_user");
|
||||
res.set_content("Hello, " + *user, "text/plain");
|
||||
});
|
||||
@@ -205,7 +205,7 @@ In addition to TCP, we support Unix Domain Sockets. You can use them for inter-p
|
||||
// Server
|
||||
httplib::Server svr;
|
||||
svr.set_address_family(AF_UNIX);
|
||||
svr.listen("/tmp/httplib.sock", 0);
|
||||
svr.listen("/tmp/httplib.sock", 80); // The port is unused, but must not be 0
|
||||
```
|
||||
|
||||
```cpp
|
||||
|
||||
@@ -17,7 +17,7 @@ auto res = cli.Post("/api/users", j.dump(), "application/json");
|
||||
|
||||
`Post()`の第2引数にJSON文字列、第3引数にContent-Typeを渡します。`Put()`や`Patch()`でも同じ形です。
|
||||
|
||||
> **Warning:** 第3引数のContent-Typeを省略すると、サーバー側でJSONとして認識されないことがあります。`"application/json"`を必ず指定しましょう。
|
||||
> **Warning:** 第3引数のContent-Typeが`"application/json"`でないと、サーバー側でJSONとして扱われないことがあります。忘れずに指定しましょう。
|
||||
|
||||
## JSONレスポンスを受け取る
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ auto res = cli.Get("/large-file",
|
||||
std::cout << std::endl;
|
||||
```
|
||||
|
||||
コールバックはデータを受信するたびに呼ばれます。`total`はContent-Lengthから取得した値で、サーバーが送ってこない場合は`0`になることがあります。その場合は進捗率が計算できないので、受信済みバイト数だけを表示するのが無難です。
|
||||
コールバックはデータを受信するたびに呼ばれます。`total`はContent-Lengthの値です。chunked転送のようにContent-Lengthのないレスポンスでは、進捗コールバックは一度も呼ばれません。
|
||||
|
||||
## アップロードの進捗
|
||||
|
||||
@@ -54,6 +54,8 @@ auto res = cli.Get("/large-file",
|
||||
});
|
||||
```
|
||||
|
||||
> **Note:** Content-Lengthのないレスポンスでは進捗コールバックが呼ばれないため、この方法は使えません。代わりに`ContentReceiver`から`false`を返して中断します。
|
||||
|
||||
> **Note:** `ContentReceiver`と進捗コールバックは同時に使えます。ファイルに書き出しながら進捗を表示したいときは、両方を渡しましょう。
|
||||
|
||||
> ファイル保存と組み合わせる具体例は[C01. レスポンスボディを取得する / ファイルに保存する](../c01-get-response-body)も参照してください。
|
||||
@@ -16,11 +16,11 @@ cli.set_max_timeout(5000); // 5秒(ミリ秒単位)
|
||||
auto res = cli.Get("/slow-endpoint");
|
||||
```
|
||||
|
||||
ミリ秒単位で指定します。接続、送信、受信をすべて含めて、リクエスト全体が指定時間を超えたら打ち切られます。
|
||||
ミリ秒単位で指定します。リクエストを始めてからこの時間が過ぎると、レスポンスを待っている途中でも打ち切られます。ただし、接続や送信で待たされる時間まで短くなるわけではありません。そちらは`set_connection_timeout`と`set_write_timeout`で調整します。
|
||||
|
||||
## `std::chrono`で指定する
|
||||
|
||||
こちらも`std::chrono`の期間を受け取るオーバーロードがあります。
|
||||
こちらにも、`std::chrono`の期間を受け取るオーバーロードがあります。
|
||||
|
||||
```cpp
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
@@ -4,43 +4,44 @@ order: 14
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
`httplib::Client`は同じインスタンスで複数回リクエストを送ると、TCP接続を自動的に再利用します。HTTP/1.1のKeep-Aliveが有効に働くので、TCPハンドシェイクやTLSハンドシェイクのオーバーヘッドを毎回払わずに済みます。
|
||||
`httplib::Client`は、デフォルトではリクエストのたびに接続を閉じます(`Connection: close`を送ります)。`set_keep_alive(true)`を呼んでおくと、同じインスタンスから送るリクエストは1本のTCP接続を使い回します。TCPやTLSのハンドシェイクを毎回やり直さずに済みます。
|
||||
|
||||
## 接続は自動で使い回される
|
||||
## Keep-Aliveを有効にする
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("https://api.example.com");
|
||||
cli.set_keep_alive(true);
|
||||
|
||||
auto res1 = cli.Get("/users/1");
|
||||
auto res2 = cli.Get("/users/2"); // 同じ接続を再利用
|
||||
auto res3 = cli.Get("/users/3"); // 同じ接続を再利用
|
||||
```
|
||||
|
||||
特別な設定は要りません。`cli`を使い回すだけで、内部的には同じソケットで通信が続きます。とくにHTTPSでは、TLSハンドシェイクのコストが大きいので効果が顕著です。
|
||||
あとは`cli`を使い回すだけで、内部的には同じソケットで通信が続きます。とくにHTTPSでは、TLSハンドシェイクのコストが大きいので効果が顕著です。
|
||||
|
||||
## Keep-Aliveを明示的にオフにする
|
||||
## Keep-Aliveをオフに戻す
|
||||
|
||||
毎回新しい接続を張り直したい場合は、`set_keep_alive(false)`を呼びます。テスト目的などで使うことがあります。
|
||||
リクエストのたびに接続を張り直す動作(デフォルト)に戻すには、`set_keep_alive(false)`を呼びます。
|
||||
|
||||
```cpp
|
||||
cli.set_keep_alive(false);
|
||||
```
|
||||
|
||||
ただし、普段はオン(デフォルト)のままで問題ありません。
|
||||
|
||||
## リクエストごとに`Client`を作らない
|
||||
|
||||
1回のリクエストのたびに`Client`をスコープから抜けて破棄すると、接続の再利用は効きません。ループの外でインスタンスを作り、中で使い回しましょう。
|
||||
リクエストのたびに`Client`を作っては破棄していると、接続は再利用されません。インスタンスはループの外で作り、中で使い回しましょう。
|
||||
|
||||
```cpp
|
||||
// NG: 毎回接続が切れる
|
||||
for (auto id : ids) {
|
||||
httplib::Client cli("https://api.example.com");
|
||||
cli.set_keep_alive(true);
|
||||
cli.Get("/users/" + id);
|
||||
}
|
||||
|
||||
// OK: 接続が再利用される
|
||||
httplib::Client cli("https://api.example.com");
|
||||
cli.set_keep_alive(true);
|
||||
for (auto id : ids) {
|
||||
cli.Get("/users/" + id);
|
||||
}
|
||||
@@ -50,4 +51,4 @@ for (auto id : ids) {
|
||||
|
||||
複数のスレッドから並行にリクエストを送りたいときは、スレッドごとに別々の`Client`インスタンスを持つのが無難です。1つの`Client`は1本のTCP接続を使い回すので、同じインスタンスに複数スレッドから同時にリクエストを投げると、結局どこかで直列化されます。
|
||||
|
||||
> **Note:** サーバー側のKeep-Aliveタイムアウトを超えると、サーバーが接続を切ります。その場合cpp-httplibは自動で再接続して再試行するので、アプリケーションコードで気にする必要はありません。
|
||||
> **Note:** サーバー側のKeep-Aliveタイムアウトを超えると、サーバーが接続を切ります。cpp-httplibは次のリクエストを送る前にそれに気付いて接続し直すので、アプリケーション側で気にする必要はありません。
|
||||
@@ -4,7 +4,7 @@ order: 15
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlibまたはBrotliを有効にしてビルドしておく必要があります。
|
||||
cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlib、Brotli、Zstdのいずれかを有効にしてビルドしておく必要があります。
|
||||
|
||||
## ビルド時の準備
|
||||
|
||||
@@ -13,10 +13,11 @@ cpp-httplibは送信時の圧縮と受信時の解凍をサポートしていま
|
||||
```cpp
|
||||
#define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate
|
||||
#define CPPHTTPLIB_BROTLI_SUPPORT // brotli
|
||||
#define CPPHTTPLIB_ZSTD_SUPPORT // zstd
|
||||
#include <httplib.h>
|
||||
```
|
||||
|
||||
リンク時に`zlib`や`brotli`のライブラリも必要です。
|
||||
有効にした方式に応じて、`zlib`、`brotli`、`zstd`のライブラリもリンクします。
|
||||
|
||||
## リクエストボディを圧縮して送る
|
||||
|
||||
@@ -28,7 +29,7 @@ std::string big_payload = build_payload();
|
||||
auto res = cli.Post("/api/data", big_payload, "application/json");
|
||||
```
|
||||
|
||||
`set_compress(true)`を呼んでおくと、POSTやPUTのリクエストボディがgzipで圧縮されて送信されます。サーバー側が対応している必要があります。
|
||||
`set_compress(true)`を呼んでおくと、POSTやPUTのリクエストボディが圧縮されて送信されます。圧縮方式は、ビルドで有効にしたもののうち、Brotli、gzip、Zstdの順で最初に当てはまるものです。サーバー側もその方式に対応している必要があります。
|
||||
|
||||
## レスポンスを解凍する
|
||||
|
||||
@@ -44,4 +45,4 @@ std::cout << res->body << std::endl;
|
||||
|
||||
デフォルトで有効なので、通常は何もしなくても解凍されます。あえて生の圧縮データを触りたいときだけ`set_decompress(false)`にしましょう。
|
||||
|
||||
> **Warning:** `CPPHTTPLIB_ZLIB_SUPPORT`を定義せずにビルドすると、`set_compress()`や`set_decompress()`を呼んでも何も起こりません。マクロの定義を忘れていないか、最初に確認しましょう。
|
||||
> **Warning:** 圧縮ライブラリを1つも有効にしていないビルドでは、`set_compress(true)`を呼んでもリクエストは圧縮されません。また、ビルドで有効にしていない方式で圧縮されたレスポンスが返ってくると、リクエストは`Error::UnsupportedContentEncoding`で失敗します。うまく動かないときは、まずマクロの定義を確認しましょう。
|
||||
@@ -55,7 +55,7 @@ cli.set_bearer_token_auth("api-token"); // エンドサーバー向け
|
||||
|
||||
```cpp
|
||||
cli.set_proxy("proxy.internal", 8080);
|
||||
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
|
||||
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
|
||||
```
|
||||
|
||||
エントリは次のいずれかです。
|
||||
|
||||
@@ -29,8 +29,8 @@ if (res) {
|
||||
| --- | --- |
|
||||
| `Error::Connection` | サーバーに接続できなかった |
|
||||
| `Error::ConnectionTimeout` | 接続タイムアウト(`set_connection_timeout`) |
|
||||
| `Error::Read` / `Error::Write` | 送受信中のエラー |
|
||||
| `Error::Timeout` | `set_max_timeout`で設定した全体タイムアウト |
|
||||
| `Error::Read` / `Error::Write` | 送受信中のエラー。`set_read_timeout`や`set_max_timeout`によるタイムアウトも`Error::Read`になる |
|
||||
| `Error::Timeout` | `stream::Get()`や`SSEClient`で、ボディの読み取りがタイムアウトした |
|
||||
| `Error::ExceedRedirectCount` | リダイレクト回数が上限を超えた |
|
||||
| `Error::SSLConnection` | TLSハンドシェイクに失敗 |
|
||||
| `Error::SSLServerVerification` | サーバー証明書の検証に失敗 |
|
||||
@@ -38,7 +38,7 @@ if (res) {
|
||||
|
||||
## ステータスコードとの使い分け
|
||||
|
||||
`res`が truthy でも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
|
||||
`res`がtruthyでも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Get("/api/data");
|
||||
|
||||
@@ -24,19 +24,24 @@ if (!res) {
|
||||
}
|
||||
```
|
||||
|
||||
`ssl_error()`はSSLライブラリが返したエラーコード(OpenSSLの`SSL_get_error()`の値など)、`ssl_backend_error()`はバックエンドがさらに詳しく提供するエラー値です。OpenSSLなら`ERR_get_error()`の値が入ります。
|
||||
`ssl_error()`は、どのTLSバックエンドでも共通のエラー種別(`httplib::tls::ErrorCode`)を`int`で返します。`ssl_backend_error()`は、バックエンドが返したエラー値そのものです。OpenSSLなら、ハンドシェイクの失敗では`ERR_get_error()`の値が、証明書検証の失敗では検証結果のコード(`X509_V_ERR_*`)が入ります。
|
||||
|
||||
## OpenSSLのエラーを文字列化する
|
||||
|
||||
`ssl_backend_error()`で取得した値を、OpenSSLの`ERR_error_string()`で文字列にするとデバッグに便利です。
|
||||
`ssl_backend_error()`の値は、OpenSSLの関数で文字列にしておくとデバッグに便利です。使う関数は失敗の種類によって変わります。
|
||||
|
||||
```cpp
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/x509.h>
|
||||
|
||||
if (res.ssl_backend_error() != 0) {
|
||||
if (res.error() == httplib::Error::SSLConnection) {
|
||||
char buf[256];
|
||||
ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf));
|
||||
std::cerr << "openssl: " << buf << std::endl;
|
||||
} else if (res.error() == httplib::Error::SSLServerVerification ||
|
||||
res.error() == httplib::Error::SSLServerHostnameVerification) {
|
||||
auto code = static_cast<long>(res.ssl_backend_error());
|
||||
std::cerr << "openssl: " << X509_verify_cert_error_string(code) << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ sse.start(); // ブロッキング
|
||||
|
||||
## イベント名で分岐する
|
||||
|
||||
サーバー側で`event:`を付けて送られてくる場合は、`on_event()`で名前ごとにハンドラを登録できます。
|
||||
サーバーが`event:`を付けてイベントを送ってくる場合は、`on_event()`で名前ごとにハンドラを登録できます。
|
||||
|
||||
```cpp
|
||||
sse.on_event("message", [](const auto &msg) {
|
||||
@@ -41,7 +41,7 @@ sse.on_event("leave", [](const auto &msg) {
|
||||
});
|
||||
```
|
||||
|
||||
`on_message()`は、名前なし(デフォルトの`message`イベント)を受け取る汎用ハンドラとして使えます。
|
||||
`on_message()`は、`on_event()`で登録していない名前のイベントをまとめて受け取る汎用ハンドラです。上の例のように`on_event("message", ...)`を登録した場合、`message`イベントは`on_message()`ではなくそちらに届きます。
|
||||
|
||||
## 接続イベントとエラーハンドリング
|
||||
|
||||
@@ -55,7 +55,7 @@ sse.on_error([](httplib::Error err) {
|
||||
});
|
||||
```
|
||||
|
||||
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。
|
||||
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。ただし、サーバーが204、403、404のいずれかを返したときは再接続しません。
|
||||
|
||||
## 非同期で動かす
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ svr.set_mount_point("/", "./public");
|
||||
svr.listen("0.0.0.0", 8080);
|
||||
```
|
||||
|
||||
`./public/index.html`が`http://localhost:8080/index.html`で、`./public/css/style.css`が`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。
|
||||
`./public/index.html`には`http://localhost:8080/index.html`で、`./public/css/style.css`には`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。
|
||||
|
||||
## 複数のマウントポイント
|
||||
|
||||
@@ -26,11 +26,11 @@ svr.set_mount_point("/assets", "./dist/assets");
|
||||
svr.set_mount_point("/uploads", "./var/uploads");
|
||||
```
|
||||
|
||||
同じパスに複数のマウントを登録することもできます。その場合は登録順に探されて、見つかった最初のものが返ります。
|
||||
同じパスに複数のマウントを登録することもできます。その場合は登録した順に探し、最初に見つかったファイルを返します。
|
||||
|
||||
## APIハンドラと組み合わせる
|
||||
|
||||
静的ファイルとAPIハンドラは共存できます。`Get()`などで登録したハンドラが優先され、マッチしなかったときにマウントポイントが探されます。
|
||||
静的ファイルとAPIハンドラは共存できます。GETとHEADのリクエストでは、まずマウントポイントからファイルを探し、見つからなければ`Get()`などで登録したハンドラを呼びます。
|
||||
|
||||
```cpp
|
||||
svr.Get("/api/users", [](const auto &req, auto &res) {
|
||||
@@ -44,7 +44,7 @@ svr.set_mount_point("/", "./public");
|
||||
|
||||
## MIMEタイプを追加する
|
||||
|
||||
拡張子からContent-Typeを決めるマッピングは組み込みですが、カスタムの拡張子を追加できます。
|
||||
拡張子からContent-Typeを決める対応表は組み込まれていますが、独自の拡張子を追加することもできます。
|
||||
|
||||
```cpp
|
||||
svr.set_file_extension_and_mimetype_mapping("wasm", "application/wasm");
|
||||
|
||||
@@ -15,14 +15,15 @@ svr.Get("/download", [](const httplib::Request &req, httplib::Response &res) {
|
||||
res.set_content_provider(
|
||||
total_size, "application/octet-stream",
|
||||
[](size_t offset, size_t length, httplib::DataSink &sink) {
|
||||
auto data = read_range_from_file("large.bin", offset, length);
|
||||
auto n = std::min(length, size_t(64 * 1024));
|
||||
auto data = read_range_from_file("large.bin", offset, n);
|
||||
sink.write(data.data(), data.size());
|
||||
return true;
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
ラムダが呼ばれるたびに`offset`と`length`が渡されるので、その範囲だけ読み込んで`sink.write()`で送ります。メモリには常に少量のチャンクしか載りません。
|
||||
ラムダは繰り返し呼ばれ、そのたびに`offset`(ここまでに送った位置)と`length`(残りのバイト数)が渡されます。`length`は残り全部を指すので、上の例のように1回に読む量を自分で区切って`sink.write()`で送ります。こうすれば、メモリに載るのは常に小さなチャンクだけです。
|
||||
|
||||
## ファイルをそのまま返す
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ svr.Post("/upload",
|
||||
});
|
||||
```
|
||||
|
||||
`content_reader`が`false`を返したら、レスポンスのステータスは自分でセットしてください。ボディの残りは読まずに接続を閉じるので、送信中のクライアントには接続が切れたように見えます。
|
||||
`content_reader`が`false`を返した場合、何もしなければステータスは400になります(ボディがサイズ上限を超えていたときは413)。ほかのステータスを返したいときは自分でセットしてください。ボディの残りは読まずに接続を閉じるので、送信中のクライアントには接続が切れたように見えます。
|
||||
|
||||
> **Warning:** `HandlerWithContentReader`を使うと、`req.body`は**空のまま**です。ボディはコールバック内で自分で処理してください。
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ svr.Get("/api/data", [](const httplib::Request &req, httplib::Response &res) {
|
||||
|
||||
## 圧縮の優先順位
|
||||
|
||||
クライアントが複数の方式を受け入れる場合、Brotli → Zstd → gzipの順に選ばれます(ビルドで有効になっている中から)。クライアント側では気にせず、一番効率の良い方式で圧縮されます。
|
||||
クライアントが複数の方式を受け入れる場合は、`Accept-Encoding`のq値がいちばん高い方式で圧縮します。q値が同じときは、ビルドで有効な方式の中からBrotli → gzip → Zstdの順に選びます。
|
||||
|
||||
## ストリーミングレスポンスも圧縮される
|
||||
|
||||
@@ -69,7 +69,7 @@ svr.set_static_file_compression_max_length(1024 * 1024);
|
||||
|
||||
どちらの境界も`0`で無効にできます。コンパイル時のデフォルトは`CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH`と`CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH`で決まります。
|
||||
|
||||
圧縮しても`Content-Length`は付いたままなので、`HEAD`は`GET`と同じサイズを返します。細かい挙動として、Rangeリクエストは非圧縮の表現から切り出して返し、`ETag`には`W/"...-gzip"`のように使われた圧縮方式が入ります。
|
||||
圧縮しても`Content-Length`は付いたままなので、`HEAD`は`GET`と同じサイズを返します。細かい点が2つあります。Rangeリクエストには圧縮前のデータから該当範囲を切り出して返します。また、`ETag`には`W/"...-gzip"`のように、使った圧縮方式が入ります。
|
||||
|
||||
なお`set_content_provider()`で登録したコンテンツプロバイダは対象外です。圧縮器を通すと、内部バッファが埋まるまで書き込みが送出されず、ボディを少しずつ生成するプロバイダが止まってしまうためです。生成したボディを圧縮したい場合は`set_chunked_content_provider()`を使ってください。
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
|
||||
|
||||
## よくある型
|
||||
|
||||
`std::string`、数値、構造体、`std::shared_ptr`など、コピーかムーブできる値なら何でも入れられます。
|
||||
`std::string`、数値、構造体、`std::shared_ptr`など、コピーできる値なら何でも入れられます。
|
||||
|
||||
```cpp
|
||||
res.user_data.set("user_id", std::string{"42"});
|
||||
@@ -51,6 +51,6 @@ res.user_data.set("started_at", std::chrono::steady_clock::now());
|
||||
|
||||
## 注意点
|
||||
|
||||
`user_data`は`Response`に乗っています(`req.user_data`ではありません)。これは、ハンドラには`Response&`として可変参照が渡されるためです。一見不思議ですが、「ハンドラ間で共有する可変コンテキスト」として覚えておくと素直です。
|
||||
`user_data`は`Response`に乗っています(`req.user_data`ではありません)。これは、ハンドラには`Response&`として可変参照が渡されるためです。一見不思議ですが、「ハンドラ間で共有する可変コンテキスト」だと考えると納得がいきます。
|
||||
|
||||
> **Warning:** `user_data.get<T>()`は型が一致しないと`nullptr`を返します。保存時と取得時で同じ型を指定してください。`AuthUser`で入れて`const AuthUser`で取ろうとすると失敗します。
|
||||
@@ -48,7 +48,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
||||
auto *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
|
||||
auto elapsed = start
|
||||
? std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
|
||||
@@ -52,6 +52,6 @@ int main() {
|
||||
|
||||
## 処理中のリクエストの扱い
|
||||
|
||||
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに処理中のリクエストは**最後まで実行**されます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
|
||||
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに動いているハンドラは**最後まで実行**されます。ただし、ストリーミングのようにコンテンツプロバイダで送っている途中のレスポンスは、その場で打ち切られます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
|
||||
|
||||
> **Warning:** `stop()`を呼んでから`listen()`が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。
|
||||
@@ -19,7 +19,7 @@ svr.Get("/", [](const auto &, auto &res) {
|
||||
svr.listen("/tmp/httplib.sock", 80);
|
||||
```
|
||||
|
||||
`set_address_family(AF_UNIX)`を呼んでから、`listen()`の第1引数にソケットファイルのパスを渡します。第2引数のポート番号は使われませんが、シグネチャの都合で何か渡す必要があります。
|
||||
`set_address_family(AF_UNIX)`を呼んでから、`listen()`の第1引数にソケットファイルのパスを渡します。第2引数のポート番号は使われませんが、省略はできません。`0`を渡すと`listen()`が失敗するので、`0`以外の適当な値を渡してください。
|
||||
|
||||
## クライアント側
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ httplib::SSLClient cli("api.example.com", 443,
|
||||
auto res = cli.Get("/");
|
||||
```
|
||||
|
||||
`Client`ではなく`SSLClient`を直接使う点に注意してください。秘密鍵にパスワードがある場合は第5引数で渡せます。
|
||||
証明書と鍵のファイルを渡すだけなら、`httplib::Client cli("https://api.example.com", "client-cert.pem", "client-key.pem")`のように`Client`でも書けます。秘密鍵にパスワードがかかっている場合は`SSLClient`を使い、第5引数にパスワードを渡します。
|
||||
|
||||
クライアント側にも同じ`PemMemory`構造体があり、メモリ上のPEMからクライアント証明書を設定できます。
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ cli.connect();
|
||||
|
||||
デフォルトのPing間隔は、ビルド時のマクロ`CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`で決まります。通常はそのままで問題ありませんが、特別なプロキシ環境に合わせて短くしたい場合は調整してください。
|
||||
|
||||
## PongはどうやってpIngに応答するか
|
||||
## Pingへの応答(Pong)
|
||||
|
||||
WebSocketプロトコルでは、PingフレームにはPongフレームで応答することが決まっています。cpp-httplibは受信したPingに自動でPongを返すので、アプリケーションコード側で気にする必要はありません。
|
||||
|
||||
@@ -55,7 +55,7 @@ WebSocketプロトコルでは、PingフレームにはPongフレームで応答
|
||||
|
||||
短すぎると無駄なトラフィックになり、長すぎると接続が切れます。だいたい**接続が切れる時間の半分**くらいが目安です。
|
||||
|
||||
> **Warning:** Ping間隔を極端に短くすると、WebSocket接続ごとにバックグラウンドでスレッドが走るので、CPU負荷が上がります。接続数が多いサーバーでは控えめな値に設定しましょう。
|
||||
> **Warning:** WebSocket接続ごとにバックグラウンドでスレッドが走るので、Ping間隔を極端に短くするとCPU負荷が上がります。接続数が多いサーバーでは控えめな値に設定しましょう。
|
||||
|
||||
## 無応答のピアを検出する
|
||||
|
||||
@@ -67,14 +67,14 @@ cli.set_websocket_max_missed_pongs(2); // 2回連続でPongが返ってこなけ
|
||||
|
||||
サーバー側にも同じ`set_websocket_max_missed_pongs()`があります。
|
||||
|
||||
たとえばPing間隔が30秒で`max_missed_pongs = 2`なら、無応答のピアは約60秒で検出され、`CloseStatus::GoingAway`(理由は`"pong timeout"`)で接続が閉じられます。
|
||||
たとえばPing間隔が30秒で`max_missed_pongs = 2`なら、相手が応答しなくなってから60〜90秒で検出され、`CloseStatus::GoingAway`(理由は`"pong timeout"`)で接続が閉じられます。このとき`read()`で受信を待っていた場合は、`Fail`が返ります。
|
||||
|
||||
この仕組みは`read()`を呼んでPongフレームを消費したタイミングでカウンタがリセットされます。つまり通常のWebSocketクライアントのように`read()`をループで回していれば、特に意識することなく動きます。
|
||||
カウンタは、`read()`がPongフレームを受け取ったタイミングでリセットされます。つまり、通常のWebSocketクライアントのように`read()`をループで回していれば、特に意識しなくても動きます。
|
||||
|
||||
### デフォルトは無効
|
||||
|
||||
`max_missed_pongs`のデフォルトは`0`で、これは「Pongが何回返ってこなくてもこの仕組みでは切断しない」という意味です。Ping自体は送られ続けますが、応答の有無はチェックされません。無応答ピアを検出したい場合は明示的に`1`以上を設定してください。
|
||||
|
||||
サーバ側は`0`のままでも接続が残り続けることはありません。ハンドラが`read()`を呼んでいる間は`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`(デフォルト**300秒 = 5分**)が保険として働きます。一方クライアント側にはこの保険がなく、読み取りタイムアウトを設定しない限り無期限に待つので、無応答ピアを検出する手段は`max_missed_pongs`だけです。どちらの側でも「**もっと速く**検出したい」ときに使うオプションでもあります。
|
||||
サーバー側は`0`のままでも接続が残り続けることはありません。ハンドラが`read()`を呼んでいる間は`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`(デフォルト**300秒 = 5分**)が保険として働きます。一方クライアント側にはこの保険がなく、読み取りタイムアウトを設定しない限り無期限に待つので、無応答ピアを検出する手段は`max_missed_pongs`だけです。どちらの側でも「**もっと速く**検出したい」ときに使うオプションでもあります。
|
||||
|
||||
> 接続が閉じたときの処理は[W03. 接続クローズをハンドリングする](../w03-websocket-close)を参照してください。
|
||||
@@ -3,7 +3,7 @@ title: "cpp-httplib"
|
||||
order: 0
|
||||
---
|
||||
|
||||
[cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h) というヘッダーファイルを1枚コピーするだけで使えます。
|
||||
[cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h)というヘッダーファイルを1枚コピーするだけで使えます。
|
||||
|
||||
C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。
|
||||
|
||||
|
||||
@@ -18,10 +18,6 @@ llama.cppのAPIを直接扱うとコードが長くなるので、薄いラッ
|
||||
int main() {
|
||||
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
|
||||
|
||||
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
// ... HTTPサーバーの構築・起動 ...
|
||||
}
|
||||
```
|
||||
@@ -78,7 +74,7 @@ svr.Post("/translate",
|
||||
});
|
||||
```
|
||||
|
||||
`llm.chat()`は推論中に例外を投げることがあります(コンテキスト長の超過など)。`try/catch`で捕捉してエラーをJSONで返すことで、サーバーがクラッシュするのを防ぎます。
|
||||
`llm.chat()`は推論中に例外を投げることがあります(コンテキスト長の超過など)。`try/catch`で捕捉して、エラーの内容をJSONで返します。捕捉しなくてもcpp-httplibが500を返してくれますが、何が起きたのかはクライアントに伝わりません。
|
||||
|
||||
## 2.3 全体のコード
|
||||
|
||||
@@ -111,10 +107,6 @@ int main() {
|
||||
// 1章でダウンロードしたモデルをロード
|
||||
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
|
||||
|
||||
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
// リクエストとレスポンスをログに記録
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
|
||||
@@ -73,7 +73,7 @@ svr.Post("/translate/stream",
|
||||
- `sink.os`に書き込んだ後、`sink.os.good()`でクライアントがまだ接続しているかを確認できます。切断されていたら`false`を返して推論を止めます
|
||||
- 各トークンは`json(token).dump()`でJSON文字列としてエスケープしてから送ります。改行やクォートを含むトークンでも安全です
|
||||
- `dump(-1, ' ', false, ...)`の最初の3つの引数はデフォルトと同じです。重要なのは第4引数の`json::error_handler_t::replace`です。LLMはトークンをサブワード単位で返すため、マルチバイト文字(日本語など)の途中でトークンが切れることがあります。不完全なUTF-8バイト列をそのまま`dump()`に渡すと例外が飛ぶので、`replace`で安全に置換します。ブラウザ側で結合されるため、表示上の問題はありません
|
||||
- `try/catch`でラムダ全体を囲んでいます。`llm.chat()`はコンテキストウィンドウの超過などで例外を投げることがあります。ラムダ内で例外が未捕捉だとサーバーがクラッシュするので、エラーをSSEイベントとして返します
|
||||
- `try/catch`でラムダ全体を囲んでいます。`llm.chat()`はコンテキストウィンドウの超過などで例外を投げることがあります。ラムダの中で例外を捕捉しないと、cpp-httplibは接続を切るだけなので、何が起きたのかクライアントにはわかりません。そこで、エラーをSSEイベントとして返します
|
||||
- `data: [DONE]`はOpenAI APIと同じ慣習で、ストリームの終了をクライアントに伝えます
|
||||
|
||||
## 3.4 全体のコード
|
||||
@@ -107,10 +107,6 @@ int main() {
|
||||
// GGUFモデルをロード
|
||||
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
|
||||
|
||||
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
// リクエストとレスポンスをログに記録
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
|
||||
@@ -219,7 +219,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true);
|
||||
cli.set_read_timeout(std::chrono::hours(1));
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -469,7 +468,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
|
||||
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -539,10 +537,6 @@ int main() {
|
||||
auto llm = llamalib::Llama{path};
|
||||
std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する
|
||||
|
||||
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
<< std::endl;
|
||||
|
||||
@@ -939,7 +939,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
|
||||
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -1008,10 +1007,6 @@ int main() {
|
||||
}
|
||||
auto llm = llamalib::Llama{path};
|
||||
|
||||
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
<< std::endl;
|
||||
|
||||
@@ -17,7 +17,7 @@ order: 6
|
||||
|
||||
モデルは初回起動時に自動ダウンロードされるので、ユーザーに渡すのはバイナリ1つだけです。
|
||||
|
||||
## 6.1 webview/webview を導入する
|
||||
## 6.1 webview/webviewを導入する
|
||||
|
||||
[webview/webview](https://github.com/webview/webview)は、OS標準のWebViewコンポーネント(macOSならWKWebView、LinuxならWebKitGTK、WindowsならWebView2)をC/C++から使えるようにするライブラリです。Electronのように独自ブラウザを同梱するわけではないので、バイナリサイズへの影響はほぼありません。
|
||||
|
||||
@@ -78,7 +78,7 @@ int main() {
|
||||
|
||||
5章の`signal_handler`は不要になります。デスクトップアプリではウインドウを閉じることがアプリの終了を意味するからです。
|
||||
|
||||
## 6.3 cpp-embedlib で静的ファイルを埋め込む
|
||||
## 6.3 cpp-embedlibで静的ファイルを埋め込む
|
||||
|
||||
5章では`public/`ディレクトリからファイルを配信していました。これだと配布時に`public/`も一緒に渡す必要があります。[cpp-embedlib](https://github.com/yhirose/cpp-embedlib)を使うと、HTML・CSS・JavaScriptをバイナリに埋め込んで、配布物をバイナリ1つにまとめられます。
|
||||
|
||||
@@ -108,7 +108,7 @@ target_link_libraries(translate-app PRIVATE
|
||||
|
||||
`cpp_embedlib_add`は、`public/`配下のファイルをコンパイル時にバイナリに変換し、`WebAssets`という静的ライブラリを作ります。リンクすると`Web::FS`というオブジェクトから埋め込みファイルにアクセスできます。`cpp-embedlib-httplib`は`httplib::mount()`関数を提供するヘルパーライブラリです。
|
||||
|
||||
### set_mount_point を httplib::mount に置き換える
|
||||
### set_mount_pointをhttplib::mountに置き換える
|
||||
|
||||
5章の`set_mount_point`をcpp-embedlibの`httplib::mount`に置き換えるだけです。
|
||||
|
||||
@@ -407,7 +407,6 @@ bool download_model(const ModelInfo &model,
|
||||
std::function<bool(int)> progress_cb) {
|
||||
httplib::Client cli("https://huggingface.co");
|
||||
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
|
||||
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -469,10 +468,6 @@ int main() {
|
||||
auto llm = llamalib::Llama{path};
|
||||
std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する
|
||||
|
||||
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
|
||||
svr.set_read_timeout(300);
|
||||
svr.set_write_timeout(300);
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
<< std::endl;
|
||||
|
||||
@@ -11,13 +11,17 @@ order: 7
|
||||
## 7.1 ソースコードの場所
|
||||
|
||||
```ascii
|
||||
llama.cpp/tools/server/
|
||||
├── server.cpp # メインのサーバー実装
|
||||
├── httplib.h # cpp-httplib(同梱版)
|
||||
└── ...
|
||||
llama.cpp/
|
||||
├── tools/server/
|
||||
│ ├── server.cpp # エントリポイント
|
||||
│ ├── server-http.cpp # HTTPサーバー(cpp-httplibを使う層)
|
||||
│ ├── server-context.cpp # 推論とスロットの管理
|
||||
│ └── ...
|
||||
└── vendor/cpp-httplib/
|
||||
└── httplib.h # cpp-httplib(同梱版)
|
||||
```
|
||||
|
||||
ファイルは1つの`server.cpp`にまとまっています。数千行ありますが、構造を知っていれば読むべき箇所は絞れます。
|
||||
実装は役割ごとにファイルが分かれています。全体では2万行を超えますが、構造を知っていれば読むべき箇所は絞れます。
|
||||
|
||||
## 7.2 OpenAI互換API
|
||||
|
||||
@@ -141,7 +145,7 @@ LLMをアプリに組み込むとき、出力を確実にパースできるか
|
||||
| SSEフォーマット | トークンのみ | OpenAI互換JSON |
|
||||
| KVキャッシュ | 毎回クリア | prefixを再利用 |
|
||||
| 構造化出力 | なし | JSON Schema/文法制約 |
|
||||
| コード量 | 約200行 | 数千行 |
|
||||
| コード量 | 約200行 | 2万行以上 |
|
||||
|
||||
私たちのコードがシンプルなのは、「デスクトップアプリで1人が使う」という前提があるからです。複数人に提供するサーバーや、既存のエコシステムと連携するサーバーを作るなら、`llama-server`の設計が参考になります。
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ CI(GitHub Actionsなど)でクロスプラットフォームビルドを自
|
||||
- **クライアント**: HTTPS接続、リダイレクト追従、コンテンツレシーバーによる大容量ダウンロード、進捗コールバック
|
||||
- **WebView連携**: `bind_to_any_port` + `listen_after_bind`でバックグラウンドスレッド化
|
||||
|
||||
cpp-httplibにはこの他にも、マルチパートによるファイルアップロード、認証、タイムアウト制御、圧縮、レンジリクエストなど便利な機能があります。詳しくは [A Tour of cpp-httplib](../../tour/) をご覧ください。
|
||||
cpp-httplibにはこの他にも、マルチパートによるファイルアップロード、認証、タイムアウト制御、圧縮、レンジリクエストなど便利な機能があります。詳しくは[A Tour of cpp-httplib](../../tour/)をご覧ください。
|
||||
|
||||
これらのパターンは翻訳アプリに限りません。自分のC++ライブラリにWeb APIを付けたい、ブラウザUIで操作できるようにしたい、配布しやすいデスクトップアプリにしたい―そんなときに、この本がリファレンスになれば嬉しいです。
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ order: 1
|
||||
|
||||
cpp-httplibを始めるのに必要なのは、`httplib.h`とC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。
|
||||
|
||||
## httplib.h の入手
|
||||
## httplib.hの入手
|
||||
|
||||
GitHubから直接ダウンロードできます。常に最新版を使ってください。
|
||||
|
||||
@@ -13,19 +13,19 @@ GitHubから直接ダウンロードできます。常に最新版を使って
|
||||
curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
|
||||
```
|
||||
|
||||
ダウンロードした `httplib.h` をプロジェクトのディレクトリに置けば、準備完了です。
|
||||
ダウンロードした`httplib.h`をプロジェクトのディレクトリに置けば、準備完了です。
|
||||
|
||||
## コンパイラーの準備
|
||||
|
||||
| OS | 開発環境 | セットアップ |
|
||||
| -- | -------- | ------------ |
|
||||
| macOS | Apple Clang | Xcode Command Line Tools (`xcode-select --install`) |
|
||||
| Ubuntu | clang++ または g++ | `apt install clang` または `apt install g++` |
|
||||
| Windows | MSVC | Visual Studio 2022 以降(C++ コンポーネントを含めてインストール) |
|
||||
| Ubuntu | clang++またはg++ | `apt install clang`または`apt install g++` |
|
||||
| Windows | MSVC | Visual Studio 2022以降(C++コンポーネントを含めてインストール) |
|
||||
|
||||
## Hello World サーバー
|
||||
## Hello Worldサーバー
|
||||
|
||||
次のコードを `server.cpp` として保存しましょう。
|
||||
次のコードを`server.cpp`として保存しましょう。
|
||||
|
||||
```cpp
|
||||
#include "httplib.h"
|
||||
@@ -70,16 +70,16 @@ cl /EHsc /std:c++17 server.cpp
|
||||
server.exe
|
||||
```
|
||||
|
||||
ブラウザで `http://localhost:8080` を開いてください。"Hello, World!" と表示されれば成功です。
|
||||
ブラウザで`http://localhost:8080`を開いてください。"Hello, World!"と表示されれば成功です。
|
||||
|
||||
`curl` でも確認できます。
|
||||
`curl`でも確認できます。
|
||||
|
||||
```sh
|
||||
curl http://localhost:8080/
|
||||
# Hello, World!
|
||||
```
|
||||
|
||||
サーバーを停止するには、ターミナルで `Ctrl+C` を押します。
|
||||
サーバーを停止するには、ターミナルで`Ctrl+C`を押します。
|
||||
|
||||
## 次のステップ
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ title: "Basic Client"
|
||||
order: 2
|
||||
---
|
||||
|
||||
cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client` を使って、GETやPOSTリクエストを送ってみましょう。
|
||||
cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client`を使って、GETやPOSTリクエストを送ってみましょう。
|
||||
|
||||
## テスト用サーバーの準備
|
||||
|
||||
@@ -77,9 +77,9 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
`httplib::Client` のコンストラクターにサーバーのアドレスを渡し、`Get()` でリクエストを送ります。戻り値の `res` からステータスコードやボディを取得できます。
|
||||
`httplib::Client`のコンストラクターにサーバーのアドレスを渡し、`Get()`でリクエストを送ります。戻り値の`res`からステータスコードやボディを取得できます。
|
||||
|
||||
対応する `curl` コマンドはこうなります。
|
||||
対応する`curl`コマンドはこうなります。
|
||||
|
||||
```sh
|
||||
curl http://localhost:8080/hi
|
||||
@@ -104,11 +104,11 @@ if (res) {
|
||||
}
|
||||
```
|
||||
|
||||
`res->body` は `std::string` なので、JSON レスポンスをパースしたい場合は [nlohmann/json](https://github.com/nlohmann/json) などの JSON ライブラリにそのまま渡せます。
|
||||
`res->body`は`std::string`なので、JSONレスポンスをパースしたい場合は[nlohmann/json](https://github.com/nlohmann/json)などのJSONライブラリにそのまま渡せます。
|
||||
|
||||
## クエリパラメーター
|
||||
|
||||
GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params` を使います。
|
||||
GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params`を使います。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
|
||||
@@ -117,7 +117,7 @@ if (res) {
|
||||
}
|
||||
```
|
||||
|
||||
`httplib::Params` を使うと、特殊文字のURLエンコードを自動で行ってくれます。
|
||||
`httplib::Params`を使うと、特殊文字のURLエンコードを自動で行ってくれます。
|
||||
|
||||
```sh
|
||||
curl "http://localhost:8080/search?q=cpp-httplib"
|
||||
@@ -126,7 +126,7 @@ curl "http://localhost:8080/search?q=cpp-httplib"
|
||||
|
||||
## パスパラメーター
|
||||
|
||||
URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま `Get()` に渡すだけです。
|
||||
URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま`Get()`に渡すだけです。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Get("/users/42");
|
||||
@@ -140,7 +140,7 @@ curl http://localhost:8080/users/42
|
||||
# User ID: 42
|
||||
```
|
||||
|
||||
テスト用サーバーには、正規表現でIDを数字のみに絞った `/files/(\d+)` もあります。
|
||||
テスト用サーバーには、正規表現でIDを数字のみに絞った`/files/(\d+)`もあります。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Get("/files/42");
|
||||
@@ -154,11 +154,11 @@ curl http://localhost:8080/files/42
|
||||
# File ID: 42
|
||||
```
|
||||
|
||||
`/files/abc` のように数字以外を渡すと404が返ります。仕組みは次章で解説します。
|
||||
`/files/abc`のように数字以外を渡すと404が返ります。仕組みは次章で解説します。
|
||||
|
||||
## リクエストヘッダー
|
||||
|
||||
カスタムHTTPヘッダーを付けるには、`httplib::Headers` を渡します。`Get()` や `Post()` のどちらでも使えます。
|
||||
カスタムHTTPヘッダーを付けるには、`httplib::Headers`を渡します。`Get()`や`Post()`のどちらでも使えます。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Get("/hi", httplib::Headers{
|
||||
@@ -172,7 +172,7 @@ curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
|
||||
|
||||
## POSTリクエスト
|
||||
|
||||
テキストデータをPOSTしてみましょう。`Post()` の第2引数にボディ、第3引数にContent-Typeを指定します。
|
||||
テキストデータをPOSTしてみましょう。`Post()`の第2引数にボディ、第3引数にContent-Typeを指定します。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Post("/post", "Hello, Server!", "text/plain");
|
||||
@@ -182,7 +182,7 @@ if (res) {
|
||||
}
|
||||
```
|
||||
|
||||
テスト用サーバーの `/post` はボディをそのまま返すので、送った文字列がそのまま返ってきます。
|
||||
テスト用サーバーの`/post`はボディをそのまま返すので、送った文字列がそのまま返ってきます。
|
||||
|
||||
```sh
|
||||
curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
|
||||
@@ -191,7 +191,7 @@ curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:
|
||||
|
||||
## フォームデータの送信
|
||||
|
||||
HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params` を使います。
|
||||
HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params`を使います。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Post("/submit", httplib::Params{
|
||||
@@ -200,12 +200,12 @@ auto res = cli.Post("/submit", httplib::Params{
|
||||
});
|
||||
if (res) {
|
||||
std::cout << res->body << std::endl;
|
||||
// age = 30
|
||||
// name = Alice
|
||||
// age = 30
|
||||
}
|
||||
```
|
||||
|
||||
これは `application/x-www-form-urlencoded` 形式で送信されます。
|
||||
これは`application/x-www-form-urlencoded`形式で送信されます。
|
||||
|
||||
```sh
|
||||
curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
|
||||
@@ -213,7 +213,7 @@ curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
|
||||
|
||||
## ファイルのPOST
|
||||
|
||||
ファイルをアップロードするには、`httplib::UploadFormDataItems` を使ってマルチパートフォームデータとして送信します。
|
||||
ファイルをアップロードするには、`httplib::UploadFormDataItems`を使ってマルチパートフォームデータとして送信します。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Post("/upload", httplib::UploadFormDataItems{
|
||||
@@ -224,7 +224,7 @@ if (res) {
|
||||
}
|
||||
```
|
||||
|
||||
`UploadFormDataItems` の各要素は `{name, content, filename, content_type}` の4つのフィールドで構成されます。
|
||||
`UploadFormDataItems`の各要素は`{name, content, filename, content_type}`の4つのフィールドで構成されます。
|
||||
|
||||
```sh
|
||||
curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
|
||||
@@ -232,7 +232,7 @@ curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:
|
||||
|
||||
## エラーハンドリング
|
||||
|
||||
ネットワーク通信では、サーバーに接続できない場合があります。`res` が有効かどうかを必ず確認しましょう。
|
||||
ネットワーク通信では、サーバーに接続できない場合があります。`res`が有効かどうかを必ず確認しましょう。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:9999"); // 存在しないポート
|
||||
@@ -241,7 +241,7 @@ auto res = cli.Get("/hi");
|
||||
if (!res) {
|
||||
// 接続エラー
|
||||
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
|
||||
// Error: Connection
|
||||
// Error: Could not establish connection
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -256,8 +256,8 @@ std::cout << res->body << std::endl;
|
||||
|
||||
エラーには2つのレベルがあります。
|
||||
|
||||
- **接続エラー**: サーバーに到達できなかった場合。`res` が偽になり、`res.error()` でエラーの種類を取得できます
|
||||
- **HTTPエラー**: サーバーからエラーステータス(404、500など)が返ってきた場合。`res` は真ですが、`res->status` を確認する必要があります
|
||||
- **接続エラー**: サーバーに到達できなかった場合。`res`が偽になり、`res.error()`でエラーの種類を取得できます
|
||||
- **HTTPエラー**: サーバーからエラーステータス(404、500など)が返ってきた場合。`res`は真ですが、`res->status`を確認する必要があります
|
||||
|
||||
## 次のステップ
|
||||
|
||||
|
||||
@@ -7,15 +7,15 @@ order: 3
|
||||
|
||||
## サーバーの起動
|
||||
|
||||
ルーティングを登録したら、最後に `svr.listen()` を呼んでサーバーを起動します。
|
||||
ルーティングを登録したら、最後に`svr.listen()`を呼んでサーバーを起動します。
|
||||
|
||||
```cpp
|
||||
svr.listen("0.0.0.0", 8080);
|
||||
```
|
||||
|
||||
第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"` を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは `"127.0.0.1"` を使います。
|
||||
第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"`を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは`"127.0.0.1"`を使います。
|
||||
|
||||
`listen()` はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで `Ctrl+C` を押すか、別スレッドから `svr.stop()` を呼ぶまでサーバーは動き続けます。
|
||||
`listen()`はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで`Ctrl+C`を押すか、別スレッドから`svr.stop()`を呼ぶまでサーバーは動き続けます。
|
||||
|
||||
## ルーティング
|
||||
|
||||
@@ -29,7 +29,7 @@ svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`svr.Get()` は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。`/hi` にGETリクエストが来たら、このラムダが呼ばれます。
|
||||
`svr.Get()`は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。`/hi`にGETリクエストが来たら、このラムダが呼ばれます。
|
||||
|
||||
HTTPメソッドごとにメソッドが用意されています。
|
||||
|
||||
@@ -40,7 +40,7 @@ svr.Put("/path", handler); // PUT
|
||||
svr.Delete("/path", handler); // DELETE
|
||||
```
|
||||
|
||||
ハンドラーのシグネチャは `(const httplib::Request &req, httplib::Response &res)` です。`auto` を使って短く書くこともできます。
|
||||
ハンドラーのシグネチャは`(const httplib::Request &req, httplib::Response &res)`です。`auto`を使って短く書くこともできます。
|
||||
|
||||
```cpp
|
||||
svr.Get("/hi", [](const auto &req, auto &res) {
|
||||
@@ -52,11 +52,11 @@ svr.Get("/hi", [](const auto &req, auto &res) {
|
||||
|
||||
## リクエストオブジェクト
|
||||
|
||||
ハンドラーの第1引数 `req` から、クライアントが送ってきた情報を読み取れます。
|
||||
ハンドラーの第1引数`req`から、クライアントが送ってきた情報を読み取れます。
|
||||
|
||||
### ボディ
|
||||
|
||||
`req.body` でリクエストボディを取得できます。型は `std::string` です。
|
||||
`req.body`でリクエストボディを取得できます。型は`std::string`です。
|
||||
|
||||
```cpp
|
||||
svr.Post("/post", [](const auto &req, auto &res) {
|
||||
@@ -67,7 +67,7 @@ svr.Post("/post", [](const auto &req, auto &res) {
|
||||
|
||||
### ヘッダー
|
||||
|
||||
`req.get_header_value()` でリクエストヘッダーの値を取得できます。
|
||||
`req.get_header_value()`でリクエストヘッダーの値を取得できます。
|
||||
|
||||
```cpp
|
||||
svr.Get("/check", [](const auto &req, auto &res) {
|
||||
@@ -78,7 +78,7 @@ svr.Get("/check", [](const auto &req, auto &res) {
|
||||
|
||||
### クエリパラメーターとフォームデータ
|
||||
|
||||
`req.get_param_value()` でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。
|
||||
`req.get_param_value()`でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。
|
||||
|
||||
```cpp
|
||||
svr.Get("/search", [](const auto &req, auto &res) {
|
||||
@@ -87,9 +87,9 @@ svr.Get("/search", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`/search?q=cpp-httplib` にアクセスすると、`q` の値は `"cpp-httplib"` になります。
|
||||
`/search?q=cpp-httplib`にアクセスすると、`q`の値は`"cpp-httplib"`になります。
|
||||
|
||||
すべてのパラメーターをループで処理したいときは、`req.params` を使います。
|
||||
すべてのパラメーターをループで処理したいときは、`req.params`を使います。
|
||||
|
||||
```cpp
|
||||
svr.Post("/submit", [](const auto &req, auto &res) {
|
||||
@@ -103,7 +103,7 @@ svr.Post("/submit", [](const auto &req, auto &res) {
|
||||
|
||||
### ファイルアップロード
|
||||
|
||||
マルチパートフォームでアップロードされたファイルは、`req.form.get_file()` で取得します。
|
||||
マルチパートフォームでアップロードされたファイルは、`req.form.get_file()`で取得します。
|
||||
|
||||
```cpp
|
||||
svr.Post("/upload", [](const auto &req, auto &res) {
|
||||
@@ -113,11 +113,11 @@ svr.Post("/upload", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`f.filename` でファイル名、`f.content` でファイルの中身にアクセスできます。
|
||||
`f.filename`でファイル名、`f.content`でファイルの中身にアクセスできます。
|
||||
|
||||
## パスパラメーター
|
||||
|
||||
URLの一部を変数として受け取りたいことがあります。たとえば `/users/42` の `42` を取得したい場合です。`:param` 記法を使うと、URLの一部をキャプチャできます。
|
||||
URLの一部を変数として受け取りたいことがあります。たとえば`/users/42`の`42`を取得したい場合です。`:param`記法を使うと、URLの一部をキャプチャできます。
|
||||
|
||||
```cpp
|
||||
svr.Get("/users/:id", [](const auto &req, auto &res) {
|
||||
@@ -126,7 +126,7 @@ svr.Get("/users/:id", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`/users/42` にアクセスすると、`req.path_params.at("id")` は `"42"` を返します。`/users/100` なら `"100"` です。
|
||||
`/users/42`にアクセスすると、`req.path_params.at("id")`は`"42"`を返します。`/users/100`なら`"100"`です。
|
||||
|
||||
複数のパスパラメーターも使えます。
|
||||
|
||||
@@ -140,7 +140,7 @@ svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
|
||||
|
||||
### 正規表現パターン
|
||||
|
||||
`:param` の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は `req.matches` で取得します。型は `std::smatch` です。
|
||||
`:param`の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は`req.matches`で取得します。型は`std::smatch`です。
|
||||
|
||||
```cpp
|
||||
// 数字のみのIDを受け付ける
|
||||
@@ -150,15 +150,15 @@ svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`/files/42` にはマッチしますが、`/files/abc` にはマッチしません。入力値を絞り込みたいときに便利です。
|
||||
`/files/42`にはマッチしますが、`/files/abc`にはマッチしません。入力値を絞り込みたいときに便利です。
|
||||
|
||||
## レスポンスの組み立て
|
||||
|
||||
ハンドラーの第2引数 `res` を使って、クライアントに返すレスポンスを組み立てます。
|
||||
ハンドラーの第2引数`res`を使って、クライアントに返すレスポンスを組み立てます。
|
||||
|
||||
### ボディとContent-Type
|
||||
|
||||
`res.set_content()` でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。
|
||||
`res.set_content()`でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。
|
||||
|
||||
```cpp
|
||||
svr.Get("/hi", [](const auto &req, auto &res) {
|
||||
@@ -168,7 +168,7 @@ svr.Get("/hi", [](const auto &req, auto &res) {
|
||||
|
||||
### ステータスコード
|
||||
|
||||
ステータスコードを変えたいときは、`res.status` に代入します。
|
||||
ステータスコードを変えたいときは、`res.status`に代入します。
|
||||
|
||||
```cpp
|
||||
svr.Get("/not-found", [](const auto &req, auto &res) {
|
||||
@@ -179,7 +179,7 @@ svr.Get("/not-found", [](const auto &req, auto &res) {
|
||||
|
||||
### レスポンスヘッダー
|
||||
|
||||
`res.set_header()` でレスポンスヘッダーを追加できます。
|
||||
`res.set_header()`でレスポンスヘッダーを追加できます。
|
||||
|
||||
```cpp
|
||||
svr.Get("/with-header", [](const auto &req, auto &res) {
|
||||
@@ -200,7 +200,7 @@ svr.Get("/hi", [](const auto &, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
最もシンプルなハンドラーです。リクエストの情報は使わないので、`req` の変数名を省略しています。`"Hello!"` というテキストをそのまま返します。
|
||||
最もシンプルなハンドラーです。リクエストの情報は使わないので、`req`の変数名を省略しています。`"Hello!"`というテキストをそのまま返します。
|
||||
|
||||
### GET /search
|
||||
|
||||
@@ -211,7 +211,7 @@ svr.Get("/search", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`req.get_param_value("q")` でクエリパラメーター `q` の値を取り出します。`/search?q=cpp-httplib` なら、レスポンスは `"Query: cpp-httplib"` になります。
|
||||
`req.get_param_value("q")`でクエリパラメーター`q`の値を取り出します。`/search?q=cpp-httplib`なら、レスポンスは`"Query: cpp-httplib"`になります。
|
||||
|
||||
### POST /post
|
||||
|
||||
@@ -221,7 +221,7 @@ svr.Post("/post", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body` にボディが丸ごと入っています。
|
||||
クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body`にボディが丸ごと入っています。
|
||||
|
||||
### POST /submit
|
||||
|
||||
@@ -235,7 +235,7 @@ svr.Post("/submit", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
フォームデータとして送られたキーと値のペアを、`req.params` でループ処理しています。構造化束縛 `auto &[key, val]` を使って、各ペアを取り出しています。
|
||||
フォームデータとして送られたキーと値のペアを、`req.params`でループ処理しています。構造化束縛`auto &[key, val]`を使って、各ペアを取り出しています。
|
||||
|
||||
### POST /upload
|
||||
|
||||
@@ -247,7 +247,7 @@ svr.Post("/upload", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
マルチパートフォームで送られたファイルを受け取ります。`req.form.get_file("file")` で `"file"` という名前のフィールドを取得し、`f.filename` と `f.content.size()` でファイル名とサイズを返しています。
|
||||
マルチパートフォームで送られたファイルを受け取ります。`req.form.get_file("file")`で`"file"`という名前のフィールドを取得し、`f.filename`と`f.content.size()`でファイル名とサイズを返しています。
|
||||
|
||||
### GET /users/:id
|
||||
|
||||
@@ -258,7 +258,7 @@ svr.Get("/users/:id", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`:id` の部分がパスパラメーターです。`req.path_params.at("id")` で値を取り出しています。`/users/42` なら `"42"`、`/users/alice` なら `"alice"` が得られます。
|
||||
`:id`の部分がパスパラメーターです。`req.path_params.at("id")`で値を取り出しています。`/users/42`なら`"42"`、`/users/alice`なら`"alice"`が得られます。
|
||||
|
||||
### GET /files/(\d+)
|
||||
|
||||
@@ -269,7 +269,7 @@ svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
正規表現 `(\d+)` で数字だけのIDにマッチします。`/files/42` にはマッチしますが、`/files/abc` は404になります。`req.matches[1]` で最初のキャプチャグループの値を取得しています。
|
||||
正規表現`(\d+)`で数字だけのIDにマッチします。`/files/42`にはマッチしますが、`/files/abc`は404になります。`req.matches[1]`で最初のキャプチャグループの値を取得しています。
|
||||
|
||||
## 次のステップ
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@ title: "Static File Server"
|
||||
order: 4
|
||||
---
|
||||
|
||||
cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()` を1行呼ぶだけです。
|
||||
cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()`を1行呼ぶだけです。
|
||||
|
||||
## set_mount_point の基本
|
||||
## set_mount_pointの基本
|
||||
|
||||
さっそくやってみましょう。`set_mount_point()` は、URLのパスとローカルディレクトリを紐づけます。
|
||||
さっそくやってみましょう。`set_mount_point()`は、URLのパスとローカルディレクトリを紐づけます。
|
||||
|
||||
```cpp
|
||||
#include "httplib.h"
|
||||
@@ -23,9 +23,9 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、`/` へのリクエストを `./html` ディレクトリから配信します。
|
||||
第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、`/`へのリクエストを`./html`ディレクトリから配信します。
|
||||
|
||||
試してみましょう。まず `html` ディレクトリを作って、`index.html` を置きます。
|
||||
試してみましょう。まず`html`ディレクトリを作って、`index.html`を置きます。
|
||||
|
||||
```sh
|
||||
mkdir html
|
||||
@@ -49,9 +49,9 @@ g++ -std=c++17 -o server server.cpp -pthread
|
||||
./server
|
||||
```
|
||||
|
||||
ブラウザで `http://localhost:8080` を開いてみてください。`html/index.html` の内容が表示されるはずです。`http://localhost:8080/index.html` でも同じページが返ります。
|
||||
ブラウザで`http://localhost:8080`を開いてみてください。`html/index.html`の内容が表示されるはずです。`http://localhost:8080/index.html`でも同じページが返ります。
|
||||
|
||||
もちろん、前章のクライアントコードや `curl` でもアクセスできますよ。
|
||||
もちろん、前章のクライアントコードや`curl`でもアクセスできますよ。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:8080");
|
||||
@@ -67,7 +67,7 @@ curl http://localhost:8080
|
||||
|
||||
## 複数のマウントポイント
|
||||
|
||||
`set_mount_point()` は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。
|
||||
`set_mount_point()`は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。
|
||||
|
||||
```cpp
|
||||
svr.set_mount_point("/", "./public");
|
||||
@@ -75,7 +75,7 @@ svr.set_mount_point("/assets", "./static/assets");
|
||||
svr.set_mount_point("/docs", "./documentation");
|
||||
```
|
||||
|
||||
`/assets/style.css` なら `./static/assets/style.css` を、`/docs/guide.html` なら `./documentation/guide.html` を配信します。
|
||||
`/assets/style.css`なら`./static/assets/style.css`を、`/docs/guide.html`なら`./documentation/guide.html`を配信します。
|
||||
|
||||
## ハンドラーとの組み合わせ
|
||||
|
||||
@@ -95,11 +95,11 @@ svr.set_mount_point("/", "./public");
|
||||
svr.listen("0.0.0.0", 8080);
|
||||
```
|
||||
|
||||
ハンドラーが先に評価されます。`/api/hello` にはハンドラーが応答し、それ以外のパスは `./public` ディレクトリからファイルを探します。
|
||||
リクエストが来ると、まず`./public`ディレクトリからファイルを探し、見つからなければハンドラーを呼びます。`./public/api/hello`というファイルを置かない限り、`/api/hello`にはハンドラーが応答します。
|
||||
|
||||
## レスポンスヘッダーの追加
|
||||
|
||||
`set_mount_point()` の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。
|
||||
`set_mount_point()`の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。
|
||||
|
||||
```cpp
|
||||
svr.set_mount_point("/", "./public", {
|
||||
@@ -111,7 +111,7 @@ svr.set_mount_point("/", "./public", {
|
||||
|
||||
## 静的ファイルサーバー用のDockerファイル
|
||||
|
||||
cpp-httplibのリポジトリには、静的ファイルサーバー用の `Dockerfile` が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。
|
||||
cpp-httplibのリポジトリには、静的ファイルサーバー用の`Dockerfile`が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。
|
||||
|
||||
```sh
|
||||
> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
|
||||
@@ -123,7 +123,7 @@ Press Ctrl+C to shutdown gracefully...
|
||||
192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
|
||||
```
|
||||
|
||||
`./my-site` ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。
|
||||
`./my-site`ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。
|
||||
|
||||
## 次のステップ
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ order: 5
|
||||
|
||||
## コンパイルオプション
|
||||
|
||||
TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT` マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。
|
||||
TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT`マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。
|
||||
|
||||
```sh
|
||||
# macOS (Homebrew)
|
||||
@@ -48,7 +48,7 @@ cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto
|
||||
|
||||
## 動作確認
|
||||
|
||||
ちゃんと動くか確認してみましょう。`httplib::Client` にHTTPSのURLを渡してアクセスするだけのプログラムです。
|
||||
ちゃんと動くか確認してみましょう。`httplib::Client`にHTTPSのURLを渡してアクセスするだけのプログラムです。
|
||||
|
||||
```cpp
|
||||
#define CPPHTTPLIB_OPENSSL_SUPPORT
|
||||
@@ -67,7 +67,7 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
コンパイルして実行してみてください。`Status: 200` と表示されれば、セットアップ完了です。
|
||||
コンパイルして実行してみてください。`Status: 200`と表示されれば、セットアップ完了です。
|
||||
|
||||
## 他のTLSバックエンド
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ title: "HTTPS Client"
|
||||
order: 6
|
||||
---
|
||||
|
||||
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った `httplib::Client` がそのまま使えます。コンストラクタに `https://` 付きのURLを渡すだけです。
|
||||
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った`httplib::Client`がそのまま使えます。コンストラクタに`https://`付きのURLを渡すだけです。
|
||||
|
||||
## GETリクエスト
|
||||
|
||||
@@ -27,7 +27,7 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
2章では `httplib::Client cli("http://localhost:8080")` と書きましたよね。スキームを `https://` に変えるだけです。`Get()` や `Post()` など、2章で学んだAPIはすべてそのまま使えます。
|
||||
2章では`httplib::Client cli("http://localhost:8080")`と書きましたよね。スキームを`https://`に変えるだけです。`Get()`や`Post()`など、2章で学んだAPIはすべてそのまま使えます。
|
||||
|
||||
```sh
|
||||
curl https://nghttp2.org/
|
||||
@@ -43,13 +43,13 @@ httplib::Client cli("https://localhost:8443");
|
||||
|
||||
## CA証明書の検証
|
||||
|
||||
`httplib::Client` はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
|
||||
`httplib::Client`はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
|
||||
|
||||
CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。
|
||||
|
||||
### CA証明書ファイルの指定
|
||||
|
||||
環境によってはシステムのCA証明書が見つからないこともあります。そのときは `set_ca_cert_path()` でパスを直接指定してください。
|
||||
環境によってはシステムのCA証明書が見つからないこともあります。そのときは`set_ca_cert_path()`でパスを直接指定してください。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("https://nghttp2.org");
|
||||
@@ -81,9 +81,9 @@ curl -k https://localhost:8443/
|
||||
|
||||
## リダイレクトの追跡
|
||||
|
||||
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば `http://` から `https://` へ、あるいは `www` なしから `www` ありへ転送されるケースです。
|
||||
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば`http://`から`https://`へ、あるいは`www`なしから`www`ありへ転送されるケースです。
|
||||
|
||||
デフォルトではリダイレクトを追跡しません。リダイレクト先は `Location` ヘッダーで確認できます。
|
||||
デフォルトではリダイレクトを追跡しません。リダイレクト先は`Location`ヘッダーで確認できます。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("https://nghttp2.org");
|
||||
@@ -99,7 +99,7 @@ if (res) {
|
||||
curl https://nghttp2.org/httpbin/redirect/3
|
||||
```
|
||||
|
||||
`set_follow_location(true)` を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
|
||||
`set_follow_location(true)`を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("https://nghttp2.org");
|
||||
|
||||
@@ -3,7 +3,7 @@ title: "HTTPS Server"
|
||||
order: 7
|
||||
---
|
||||
|
||||
前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の `httplib::Server` を `httplib::SSLServer` に置き換えるだけです。
|
||||
前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の`httplib::Server`を`httplib::SSLServer`に置き換えるだけです。
|
||||
|
||||
ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。
|
||||
|
||||
@@ -41,24 +41,24 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
`httplib::SSLServer` のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の `httplib::Server` とまったく同じですよ。
|
||||
`httplib::SSLServer`のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の`httplib::Server`とまったく同じですよ。
|
||||
|
||||
コンパイルして起動しましょう。
|
||||
|
||||
## 動作確認
|
||||
|
||||
サーバーが起動したら、`curl` でアクセスしてみましょう。自己署名証明書なので、`-k` オプションで証明書検証をスキップします。
|
||||
サーバーが起動したら、`curl`でアクセスしてみましょう。自己署名証明書なので、`-k`オプションで証明書検証をスキップします。
|
||||
|
||||
```sh
|
||||
curl -k https://localhost:8443/
|
||||
# Hello, HTTPS!
|
||||
```
|
||||
|
||||
ブラウザで `https://localhost:8443` を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。
|
||||
ブラウザで`https://localhost:8443`を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。
|
||||
|
||||
## クライアントからの接続
|
||||
|
||||
前章の `httplib::Client` で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。
|
||||
前章の`httplib::Client`で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。
|
||||
|
||||
### 方法1: 証明書検証を無効にする
|
||||
|
||||
@@ -82,7 +82,7 @@ int main() {
|
||||
|
||||
### 方法2: 自己署名証明書をCA証明書として指定する
|
||||
|
||||
こちらのほうが安全です。`cert.pem` をCA証明書として信頼するよう指定します。
|
||||
こちらのほうが安全です。`cert.pem`をCA証明書として信頼するよう指定します。
|
||||
|
||||
```cpp
|
||||
#define CPPHTTPLIB_OPENSSL_SUPPORT
|
||||
@@ -102,9 +102,9 @@ int main() {
|
||||
|
||||
この方法なら、指定した証明書のサーバーにだけ接続を許可して、なりすましを防げます。テスト環境でもなるべくこちらを使いましょう。
|
||||
|
||||
## Server と SSLServer の比較
|
||||
## ServerとSSLServerの比較
|
||||
|
||||
3章で学んだ `httplib::Server` のAPIは、`httplib::SSLServer` でもそのまま使えます。違いはコンストラクタだけです。
|
||||
3章で学んだ`httplib::Server`のAPIは、`httplib::SSLServer`でもそのまま使えます。違いはコンストラクタだけです。
|
||||
|
||||
| | `httplib::Server` | `httplib::SSLServer` |
|
||||
| -- | ------------------ | -------------------- |
|
||||
|
||||
@@ -30,13 +30,13 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
`svr.WebSocket()` でWebSocketハンドラーを登録します。3章の `svr.Get()` や `svr.Post()` と同じ感覚ですね。
|
||||
`svr.WebSocket()`でWebSocketハンドラーを登録します。3章の`svr.Get()`や`svr.Post()`と同じ感覚ですね。
|
||||
|
||||
ハンドラーの中では、`ws.read(msg)` でメッセージを待ちます。接続が閉じられると `read()` が `false` を返すので、ループを抜けます。`ws.send(msg)` でメッセージを送り返します。
|
||||
ハンドラーの中では、`ws.read(msg)`でメッセージを待ちます。接続が閉じられると`read()`が`false`を返すので、ループを抜けます。`ws.send(msg)`でメッセージを送り返します。
|
||||
|
||||
## クライアントからの接続
|
||||
|
||||
`httplib::ws::WebSocketClient` を使ってサーバーに接続してみましょう。
|
||||
`httplib::ws::WebSocketClient`を使ってサーバーに接続してみましょう。
|
||||
|
||||
```cpp
|
||||
#include "httplib.h"
|
||||
@@ -63,11 +63,11 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
コンストラクタには `ws://host:port/path` 形式のURLを渡します。`connect()` で接続を開始し、`send()` と `read()` でメッセージをやり取りします。
|
||||
コンストラクタには`ws://host:port/path`形式のURLを渡します。`connect()`で接続を開始し、`send()`と`read()`でメッセージをやり取りします。
|
||||
|
||||
## テキストとバイナリ
|
||||
|
||||
WebSocketにはテキストとバイナリの2種類のメッセージがあります。`read()` の戻り値で区別できます。
|
||||
WebSocketにはテキストとバイナリの2種類のメッセージがあります。`read()`の戻り値で区別できます。
|
||||
|
||||
```cpp
|
||||
svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
|
||||
@@ -90,7 +90,7 @@ svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
|
||||
|
||||
## リクエスト情報へのアクセス
|
||||
|
||||
ハンドラーの第1引数 `req` から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。
|
||||
ハンドラーの第1引数`req`から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。
|
||||
|
||||
```cpp
|
||||
svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
|
||||
@@ -111,7 +111,7 @@ svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws)
|
||||
|
||||
## WSSで使う
|
||||
|
||||
HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は `httplib::SSLServer` にWebSocketハンドラーを登録するだけです。
|
||||
HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は`httplib::SSLServer`にWebSocketハンドラーを登録するだけです。
|
||||
|
||||
```cpp
|
||||
httplib::SSLServer svr("cert.pem", "key.pem");
|
||||
@@ -126,7 +126,7 @@ svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
|
||||
svr.listen("0.0.0.0", 8443);
|
||||
```
|
||||
|
||||
クライアント側は `wss://` スキームを使います。
|
||||
クライアント側は`wss://`スキームを使います。
|
||||
|
||||
```cpp
|
||||
httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
|
||||
@@ -134,7 +134,7 @@ httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
|
||||
|
||||
## 次のステップ
|
||||
|
||||
WebSocketの基本がわかりましたね。ここまでで Tourは終わりです。
|
||||
WebSocketの基本がわかりましたね。ここまででTourは終わりです。
|
||||
|
||||
次のページでは、Tourで取り上げなかった機能をまとめて紹介します。
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Tourお疲れさまでした! cpp-httplibの基本はひと通り押さえま
|
||||
|
||||
## Streaming API
|
||||
|
||||
LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()` を使えば、データをチャンクごとに処理できます。
|
||||
LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()`を使えば、データをチャンクごとに処理できます。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:11434");
|
||||
@@ -21,7 +21,7 @@ if (result) {
|
||||
}
|
||||
```
|
||||
|
||||
`Get()` に `content_receiver` コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。
|
||||
`Get()`に`content_receiver`コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:8080");
|
||||
@@ -32,7 +32,7 @@ cli.Get("/stream", [](const char *data, size_t len) {
|
||||
});
|
||||
```
|
||||
|
||||
サーバー側には `set_content_provider()` と `set_chunked_content_provider()` があります。サイズがわかっているなら前者、不明なら後者を使ってください。
|
||||
サーバー側には`set_content_provider()`と`set_chunked_content_provider()`があります。サイズがわかっているなら前者、不明なら後者を使ってください。
|
||||
|
||||
```cpp
|
||||
// サイズ指定あり(Content-Length が設定される)
|
||||
@@ -50,12 +50,12 @@ svr.Get("/stream", [](const auto &, auto &res) {
|
||||
res.set_chunked_content_provider("text/plain",
|
||||
[](size_t offset, httplib::DataSink &sink) {
|
||||
sink.write("chunk\n", 6);
|
||||
return true; // falseを返すと終了
|
||||
return true; // 終了するときはsink.done()を呼ぶ
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
大きなファイルのアップロードには `make_file_provider()` が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。
|
||||
大きなファイルのアップロードには`make_file_provider()`が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:8080");
|
||||
@@ -67,7 +67,7 @@ auto res = cli.Post("/upload", {}, {}, {
|
||||
|
||||
## Server-Sent Events (SSE)
|
||||
|
||||
SSEクライアントも用意しています。自動再接続や `Last-Event-ID` による再開にも対応しています。
|
||||
SSEクライアントも用意しています。自動再接続や`Last-Event-ID`による再開にも対応しています。
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:8080");
|
||||
@@ -155,12 +155,12 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
});
|
||||
|
||||
svr.set_post_routing_handler([](const auto &req, auto &res) {
|
||||
// レスポンスが返された後に実行される
|
||||
// レスポンスを送信する直前に実行される
|
||||
res.set_header("X-Server", "cpp-httplib");
|
||||
});
|
||||
```
|
||||
|
||||
`res.user_data` を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。
|
||||
`res.user_data`を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。
|
||||
|
||||
```cpp
|
||||
svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
@@ -168,7 +168,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
|
||||
svr.Get("/me", [](const auto &req, auto &res) {
|
||||
svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
|
||||
auto *user = res.user_data.get<std::string>("auth_user");
|
||||
res.set_content("Hello, " + *user, "text/plain");
|
||||
});
|
||||
@@ -205,7 +205,7 @@ TCP以外に、Unix Domain Socketでの通信にも対応しています。同
|
||||
// サーバー
|
||||
httplib::Server svr;
|
||||
svr.set_address_family(AF_UNIX);
|
||||
svr.listen("/tmp/httplib.sock", 0);
|
||||
svr.listen("/tmp/httplib.sock", 80); // ポート番号は使われない(0以外を渡す)
|
||||
```
|
||||
|
||||
```cpp
|
||||
|
||||
@@ -5,11 +5,11 @@ order: 0
|
||||
|
||||
cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。
|
||||
|
||||
1. [Getting Started](01-getting-started) — httplib.h の入手とHello Worldサーバー
|
||||
1. [Getting Started](01-getting-started) — httplib.hの入手とHello Worldサーバー
|
||||
2. [Basic Client](02-basic-client) — GET/POST・パスパラメーターのリクエスト送信
|
||||
3. [Basic Server](03-basic-server) — ルーティング、パスパラメーター、レスポンスの組み立て
|
||||
4. [Static File Server](04-static-file-server) — 静的ファイルの配信
|
||||
5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLS のセットアップ
|
||||
5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLSのセットアップ
|
||||
6. [HTTPS Client](06-https-client) — HTTPSサイトへのリクエスト
|
||||
7. [HTTPS Server](07-https-server) — HTTPSサーバーの構築
|
||||
8. [WebSocket](08-websocket) — WebSocket通信の基本
|
||||
|
||||
@@ -146,6 +146,22 @@ if(HTTPLIB_IS_USING_OPENSSL)
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND_ERROR_IS_FATAL ANY
|
||||
)
|
||||
# cert_san_types.pem: the bytes of each SAN read as the other type:
|
||||
# DNS:a.zz is 97.46.122.122, IP:42.46.122.122 is "*.zz".
|
||||
execute_process(
|
||||
COMMAND ${OPENSSL_COMMAND} req -x509 -key key.pem -sha256 -days 3650 -nodes -subj /CN=san-types -addext subjectAltName=DNS:a.zz,IP:42.46.122.122 -out cert_san_types.pem
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND_ERROR_IS_FATAL ANY
|
||||
)
|
||||
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not
|
||||
# leftmost. "*.leftmost.example.test" matches a single
|
||||
# label; the wildcard in "www.*.example.test" must not be
|
||||
# honoured.
|
||||
execute_process(
|
||||
COMMAND ${OPENSSL_COMMAND} req -x509 -key key.pem -sha256 -days 3650 -nodes -subj /CN=wildcard-san -addext subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test -out cert_wildcard_san.pem
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND_ERROR_IS_FATAL ANY
|
||||
)
|
||||
endif()
|
||||
|
||||
add_subdirectory(fuzzing)
|
||||
@@ -33,3 +33,12 @@ openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=127.0.0.1" -
|
||||
# different address. The SAN address must match; the CN address
|
||||
# must be ignored.
|
||||
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=::1" -addext "subjectAltName=IP:2001:db8::1" -out cert_ipv6.pem
|
||||
|
||||
# cert_san_types.pem: the bytes of each SAN read as the other type:
|
||||
# DNS:a.zz is 97.46.122.122, IP:42.46.122.122 is "*.zz".
|
||||
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=san-types" -addext "subjectAltName=DNS:a.zz,IP:42.46.122.122" -out cert_san_types.pem
|
||||
|
||||
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not leftmost.
|
||||
# "*.leftmost.example.test" matches a single label; the
|
||||
# wildcard in "www.*.example.test" must not be honoured.
|
||||
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=wildcard-san" -addext "subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test" -out cert_wildcard_san.pem
|
||||
+22
-1
@@ -137,6 +137,25 @@ cert_ipv6_pem = custom_target(
|
||||
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=::1', '-addext', 'subjectAltName=IP:2001:db8::1', '-out', '@OUTPUT@']
|
||||
)
|
||||
|
||||
# cert_san_types.pem: the bytes of each SAN read as the other type: DNS:a.zz is
|
||||
# 97.46.122.122, IP:42.46.122.122 is "*.zz".
|
||||
cert_san_types_pem = custom_target(
|
||||
'cert_san_types_pem',
|
||||
input: key_pem,
|
||||
output: 'cert_san_types.pem',
|
||||
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=san-types', '-addext', 'subjectAltName=DNS:a.zz,IP:42.46.122.122', '-out', '@OUTPUT@']
|
||||
)
|
||||
|
||||
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not leftmost.
|
||||
# "*.leftmost.example.test" matches a single label; the wildcard in
|
||||
# "www.*.example.test" must not be honoured.
|
||||
cert_wildcard_san_pem = custom_target(
|
||||
'cert_wildcard_san_pem',
|
||||
input: key_pem,
|
||||
output: 'cert_wildcard_san.pem',
|
||||
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=wildcard-san', '-addext', 'subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test', '-out', '@OUTPUT@']
|
||||
)
|
||||
|
||||
# Copy test files to the build directory
|
||||
configure_file(input: 'ca-bundle.crt', output: 'ca-bundle.crt', copy: true)
|
||||
configure_file(input: 'image.jpg', output: 'image.jpg', copy: true)
|
||||
@@ -178,7 +197,9 @@ test(
|
||||
client_encrypted_pbes1_key_pem,
|
||||
client_encrypted_cert_pem,
|
||||
cert_ip_cn_pem,
|
||||
cert_ipv6_pem
|
||||
cert_ipv6_pem,
|
||||
cert_san_types_pem,
|
||||
cert_wildcard_san_pem
|
||||
],
|
||||
workdir: meson.current_build_dir(),
|
||||
timeout: 300
|
||||
|
||||
+1578
-270
File diff suppressed because it is too large.
Load diff
@@ -179,18 +179,20 @@ protected:
|
||||
TEST_F(WebSocketPongTimeoutTest, ClientDetectsNonResponsivePeer) {
|
||||
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
|
||||
client.set_websocket_max_missed_pongs(2);
|
||||
// A read timeout asked for at runtime is reported as Timeout, so it cannot
|
||||
// be mistaken for the Fail a pong timeout produces.
|
||||
client.set_read_timeout(10);
|
||||
ASSERT_TRUE(client.connect());
|
||||
ASSERT_TRUE(client.is_open());
|
||||
|
||||
// Client pings every 1s (compile-time default in this test file).
|
||||
// With max_missed_pongs = 2, the heartbeat thread should self-close within
|
||||
// roughly 3s. Poll is_open() up to 6s.
|
||||
// roughly 3s, and that has to end a read() already waiting on the peer.
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (client.is_open() &&
|
||||
std::chrono::steady_clock::now() - start < std::chrono::seconds(6)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
|
||||
std::string msg;
|
||||
EXPECT_EQ(client.read(msg), ws::Fail);
|
||||
EXPECT_TRUE(std::chrono::steady_clock::now() - start <
|
||||
std::chrono::seconds(6));
|
||||
EXPECT_FALSE(client.is_open());
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user