mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-19 11:19:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74ef3c4218 | ||
|
|
f17d314979 | ||
|
|
ebcd5551fd | ||
|
|
d99c697be6 | ||
|
|
344aceb446 | ||
|
|
696b94b5ed | ||
|
|
801bf2e0d2 | ||
|
|
03fa890a2e | ||
|
|
1d5f0323b1 | ||
|
|
cc9d67404e | ||
|
|
2e3cb0f985 | ||
|
|
07edfb86b4 | ||
|
|
106edcf606 | ||
|
|
906a7bf04e | ||
|
|
3744227de2 | ||
|
|
30879bb48b | ||
|
|
9bfd2ddf1c | ||
|
|
94cf1b5c9a | ||
|
|
7220bdb8b2 | ||
|
|
7234944098 | ||
|
|
e97165b5dc | ||
|
|
062666f3a1 | ||
|
|
e4b3865387 | ||
|
|
28f39225fc | ||
|
|
87940631e2 | ||
|
|
4836eb0fa5 | ||
|
|
d00af3f4e6 | ||
|
|
958f9aa82b | ||
|
|
f1c5068ee8 | ||
|
|
3b9931a85c | ||
|
|
2594f17983 | ||
|
|
0b382e353e | ||
|
|
cf409f7bab | ||
|
|
26febe0769 | ||
|
|
a09e00b03d | ||
|
|
8ca46a4db5 | ||
|
|
560126bffc | ||
|
|
be5043a240 | ||
|
|
7bf66db6ca | ||
|
|
645bdab90e | ||
|
|
567e099361 | ||
|
|
c52881cb1f | ||
|
|
bb13a3bc76 | ||
|
|
a1d4ccedea | ||
|
|
28741cb9d1 | ||
|
|
9a08b01ed7 | ||
|
|
a7fce92ed0 | ||
|
|
489fe8e504 | ||
|
|
9724ea6b2e | ||
|
|
bf08ec763c | ||
|
|
f29721c7d8 | ||
|
|
ad6c851d19 | ||
|
|
35342285a0 | ||
|
|
a10338a6ee | ||
|
|
aa0a588ed5 | ||
|
|
fb439bda2e | ||
|
|
079f2176af | ||
|
|
f18f0b7576 | ||
|
|
b4ef313cc7 | ||
|
|
9a3c1febee | ||
|
|
6529de1a91 | ||
|
|
43c9c6ddf3 | ||
|
|
bc837b87fc | ||
|
|
8f21292d16 | ||
|
|
589b028022 | ||
|
|
aa3aeb8ec3 | ||
|
|
300c084d6f | ||
|
|
ae169c6253 | ||
|
|
ceedf6ac22 | ||
|
|
66266b80c6 | ||
|
|
44658e660b | ||
|
|
3782a9f1cd | ||
|
|
f361a08f67 | ||
|
|
7c44a7a5e1 | ||
|
|
fcf7568230 | ||
|
|
314e5577b8 | ||
|
|
07c3e8c9e0 | ||
|
|
0fe883da97 | ||
|
|
7ce6c6438a | ||
|
|
162b87f325 | ||
|
|
ce7ecb633b | ||
|
|
5d10305218 | ||
|
|
aaccde2122 | ||
|
|
eeaae4bc3c | ||
|
|
455166314b | ||
|
|
3420ba8fca | ||
|
|
58957ae4da | ||
|
|
64bebd3b2b | ||
|
|
d5851d7e89 | ||
|
|
cadcc425b8 | ||
|
|
f5e11024da | ||
|
|
672255619b | ||
|
|
b270564c18 | ||
|
|
0116be0a2b | ||
|
|
194f392417 | ||
|
|
d41d5586cf | ||
|
|
82e28aa4f3 | ||
|
|
a445ed23bf | ||
|
|
f6420979b2 | ||
|
|
6acdc6255d | ||
|
|
5d10095944 | ||
|
|
65dbca0afe | ||
|
|
5056242a4b | ||
|
|
0c583ac9b5 | ||
|
|
9f6dcf1230 | ||
|
|
e225d1876b | ||
|
|
9c51a0effa | ||
|
|
41fada8c6e | ||
|
|
d78a3cbb82 | ||
|
|
2b66aa65e1 | ||
|
|
344311c1c3 | ||
|
|
2e278fd6e9 | ||
|
|
b917676861 | ||
|
|
fc0e8230ba | ||
|
|
c11d95b26b | ||
|
|
6fc677444f | ||
|
|
e3749669bc | ||
|
|
16f9d4a68d | ||
|
|
4a1700cb5e | ||
|
|
c03af246fc | ||
|
|
2c918f27ee | ||
|
|
924b5cecf0 | ||
|
|
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 | ||
|
|
91c55a4385 | ||
|
|
ad88645a83 | ||
|
|
82722fcb13 | ||
|
|
8b872605e0 | ||
|
|
52f214bf2e | ||
|
|
09c02f1335 | ||
|
|
2e5480ad65 | ||
|
|
4cb363e3f2 | ||
|
|
deb520e26b | ||
|
|
f37a5b1407 | ||
|
|
f15992c7ed | ||
|
|
278c2979e8 | ||
|
|
6b8c3f5387 | ||
|
|
e640f8376b | ||
|
|
73a4092f8a | ||
|
|
3517f92e2f | ||
|
|
0480ff77b8 | ||
|
|
8d25b6a3ac | ||
|
|
515b8f84af | ||
|
|
88956ccad8 | ||
|
|
f83d06538b | ||
|
|
dc41dbd954 | ||
|
|
6303a99ce1 | ||
|
|
d5f8858731 | ||
|
|
199d7ee248 | ||
|
|
9e2e33da56 | ||
|
|
7d53a31d23 | ||
|
|
9d6a7ee2c1 | ||
|
|
9ce15a14e5 |
No files matched your search
@@ -31,12 +31,19 @@ env:
|
||||
|
||||
jobs:
|
||||
style-check:
|
||||
runs-on: ubuntu-latest
|
||||
# Uses the macOS runner's pre-installed Homebrew so clang-format tracks
|
||||
# whatever version `brew install clang-format` currently resolves to on
|
||||
# the maintainer's own Mac, instead of a version pinned in this file.
|
||||
runs-on: macos-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: install clang-format
|
||||
run: |
|
||||
brew update
|
||||
brew install clang-format coreutils
|
||||
- name: run style check
|
||||
run: |
|
||||
clang-format --version
|
||||
@@ -475,7 +482,6 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
if: >
|
||||
(github.event_name == 'push') ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
@@ -585,7 +591,6 @@ jobs:
|
||||
- name: Build ${{ matrix.config.name }}
|
||||
run: cmake --build build --config Release -- /v:m /clp:ShowCommandLine
|
||||
- name: Run tests ${{ matrix.config.name }}
|
||||
id: run_tests
|
||||
if: ${{ matrix.config.run_tests }}
|
||||
shell: pwsh
|
||||
working-directory: build/test
|
||||
@@ -618,34 +623,6 @@ jobs:
|
||||
}
|
||||
if ($failed) { exit 1 }
|
||||
Write-Host "All shards passed."
|
||||
- name: Report flaky failure on issue #2533
|
||||
if: >
|
||||
failure() && steps.run_tests.conclusion == 'failure'
|
||||
&& matrix.config.name == 'without SSL'
|
||||
&& github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
shell: pwsh
|
||||
working-directory: build/test
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
$summary = ""
|
||||
for ($i = 0; $i -lt 4; $i++) {
|
||||
$log = "shard_${i}.log"
|
||||
if (Test-Path $log) {
|
||||
$failedLines = Select-String -Path $log -Pattern "\[ FAILED \]"
|
||||
if ($failedLines) {
|
||||
$summary += "**Shard ${i}:**`n" + (($failedLines | ForEach-Object { $_.Line }) -join "`n") + "`n`n"
|
||||
}
|
||||
}
|
||||
}
|
||||
if (-not $summary) {
|
||||
Write-Host "No [ FAILED ] line in any shard log; not a test failure. Skipping the report."
|
||||
exit 0
|
||||
}
|
||||
$runUrl = "$($env:GITHUB_SERVER_URL)/$($env:GITHUB_REPOSITORY)/actions/runs/$($env:GITHUB_RUN_ID)"
|
||||
$body = "Reoccurred on push: $runUrl`n`nCommit: $($env:GITHUB_SHA)`n`n$summary"
|
||||
gh issue comment 2533 --repo $env:GITHUB_REPOSITORY --body $body
|
||||
|
||||
env:
|
||||
VCPKG_ROOT: "C:/vcpkg"
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/mirrors-clang-format
|
||||
rev: v18.1.8 # 最新バージョンを使用
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: clang-format
|
||||
files: \.(cpp|cc|h)$
|
||||
args: [-i] # インプレースで修正
|
||||
name: clang-format
|
||||
# Uses whatever `clang-format` resolves to on PATH (the Homebrew
|
||||
# install on macOS) instead of a version pinned here, so it tracks
|
||||
# the same version CI installs via `brew install clang-format`.
|
||||
entry: clang-format
|
||||
language: system
|
||||
files: ^(httplib\.h|(example|fuzzing|test)/[^/]+\.(cpp|cc|h))$
|
||||
args: [-i]
|
||||
+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
|
||||
|
||||
+10
-4
@@ -4,7 +4,7 @@ A simple, EventSource-like SSE client for C++11.
|
||||
|
||||
## Features
|
||||
|
||||
- **Auto-reconnect**: Automatically reconnects on connection loss
|
||||
- **Auto-reconnect**: Automatically reconnects on connection loss or an error status (except 204, 403 and 404)
|
||||
- **Last-Event-ID**: Sends last received ID on reconnect for resumption
|
||||
- **retry field**: Respects server's reconnect interval
|
||||
- **Event types**: Supports custom event types via `on_event()`
|
||||
@@ -52,7 +52,7 @@ SSEClient(Client &client, const std::string &path, const Headers &headers);
|
||||
#### Event Handlers
|
||||
|
||||
```cpp
|
||||
// Called for all events (or events without a specific handler)
|
||||
// Called for events whose type has no on_event() handler
|
||||
sse.on_message([](const SSEMessage &msg) { });
|
||||
|
||||
// Called for specific event types
|
||||
@@ -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)
|
||||
@@ -79,6 +79,10 @@ sse.set_max_reconnect_attempts(10);
|
||||
sse.set_headers({{"Authorization", "Bearer new_token"}});
|
||||
```
|
||||
|
||||
The client reconnects when it cannot connect or the stream ends. A status other than `200` calls `on_error(Error::Connection)`; a `204`, `403` or `404` then stops the client, and any other status, `401` included, reconnects, so an `on_error` handler can refresh credentials with `set_headers()`. `set_max_reconnect_attempts()` counts reconnect attempts in a row: the count starts over after each successful connection. Each attempt that fails to connect is also reported to the `Client`'s error logger.
|
||||
|
||||
An event, or a line still waiting for its end, longer than `CPPHTTPLIB_SSE_MAX_EVENT_LENGTH` (16MB by default, `0` for no limit) ends the connection with `Error::ExceedMaxPayloadSize`, and the client stops rather than reconnect to the same event. The client's `set_payload_max_length()` does not apply to the stream as a whole, which has no end.
|
||||
|
||||
#### Control
|
||||
|
||||
```cpp
|
||||
@@ -157,6 +161,8 @@ httplib::sse::SSEClient sse(cli, "/events", headers);
|
||||
sse.start();
|
||||
```
|
||||
|
||||
The `Client`'s `set_basic_auth()` and `set_bearer_token_auth()` apply too; an `Authorization` header passed like this takes precedence.
|
||||
|
||||
### Refreshing Auth Token on Reconnect
|
||||
|
||||
```cpp
|
||||
@@ -191,7 +197,7 @@ sse.start();
|
||||
|
||||
## SSE Protocol
|
||||
|
||||
The client parses SSE format according to the [W3C specification](https://html.spec.whatwg.org/multipage/server-sent-events.html):
|
||||
The client parses SSE format according to the [WHATWG HTML Living Standard](https://html.spec.whatwg.org/multipage/server-sent-events.html):
|
||||
|
||||
```
|
||||
event: custom-type
|
||||
|
||||
+59
-13
@@ -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.
|
||||
|
||||
@@ -14,7 +14,7 @@ The streaming API allows you to process HTTP response bodies chunk by chunk usin
|
||||
|
||||
- **LLM/AI streaming responses** (e.g., ChatGPT, Claude, Ollama)
|
||||
- **Server-Sent Events (SSE)**
|
||||
- **Large file downloads** with progress tracking
|
||||
- **Large file downloads** with progress tracking (mind the [payload size limit](#payload-size-limit))
|
||||
- **Reverse proxy implementations**
|
||||
|
||||
## Quick Start
|
||||
@@ -62,7 +62,7 @@ cpp-httplib provides multiple API layers for different use cases:
|
||||
| Use Case | Recommended API |
|
||||
|----------|----------------|
|
||||
| SSE with auto-reconnect | `SSEClient` (see [README-sse.md](README-sse.md)) |
|
||||
| LLM streaming (JSON Lines) | `stream::Get()` |
|
||||
| LLM streaming (JSON Lines) | `stream::Post()` or `stream::Get()` |
|
||||
| Large file download | `stream::Get()` or `open_stream()` |
|
||||
| Reverse proxy | `open_stream()` |
|
||||
| Small responses with Keep-Alive | `Client::Get()` |
|
||||
@@ -106,6 +106,8 @@ if (handle.is_valid()) {
|
||||
| `get_read_error()` | `Error` | Get the last read error |
|
||||
| `has_read_error()` | `bool` | Check if a read error occurred |
|
||||
|
||||
For a chunked response, the trailers are in `response->trailers` once `read()` has reached the end of the body.
|
||||
|
||||
### High-Level API: `stream::Get()` and `stream::Result`
|
||||
|
||||
The `httplib.h` header provides a more ergonomic iterator-style API.
|
||||
@@ -114,7 +116,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
|
||||
@@ -138,6 +139,30 @@ if (result2) {
|
||||
}
|
||||
```
|
||||
|
||||
#### Helpers
|
||||
|
||||
There is a helper for each HTTP method. The arguments in brackets can be left out, and every helper takes a trailing `size_t chunk_size = 8192`, the most bytes one `next()` returns.
|
||||
|
||||
| Helper | Arguments |
|
||||
|--------|-----------|
|
||||
| `stream::Get()` | `(cli, path, [params], [headers], [chunk_size])` |
|
||||
| `stream::Head()` | `(cli, path, [params], [headers], [chunk_size])` |
|
||||
| `stream::Options()` | `(cli, path, [params], [headers], [chunk_size])` |
|
||||
| `stream::Post()` | `(cli, path, [params], [headers], body, content_type, [chunk_size])` |
|
||||
| `stream::Put()` | `(cli, path, [params], [headers], body, content_type, [chunk_size])` |
|
||||
| `stream::Patch()` | `(cli, path, [params], [headers], body, content_type, [chunk_size])` |
|
||||
| `stream::Delete()` | `(cli, path, [params], [headers], [chunk_size])` |
|
||||
| `stream::Delete()` | `(cli, path, [params], [headers], body, content_type, [chunk_size])` |
|
||||
|
||||
`params` is a `Params`, `headers` a `Headers`, and `body` and `content_type` are `std::string`s.
|
||||
|
||||
```cpp
|
||||
// POST a JSON body and stream the response in 4KB chunks
|
||||
auto result3 = httplib::stream::Post(cli, "/api/generate", headers,
|
||||
R"({"prompt": "hello"})",
|
||||
"application/json", 4096);
|
||||
```
|
||||
|
||||
#### stream::Result Members
|
||||
|
||||
| Member | Type | Description |
|
||||
@@ -217,6 +242,7 @@ int main() {
|
||||
|
||||
int main() {
|
||||
httplib::Client cli("http://example.com");
|
||||
cli.set_payload_max_length(0); // No limit (the default is 100MB)
|
||||
auto result = httplib::stream::Get(cli, "/large-file.zip");
|
||||
|
||||
if (!result || result.status() != 200) {
|
||||
@@ -233,6 +259,12 @@ int main() {
|
||||
std::cout << "\rDownloaded: " << (total / 1024) << " KB" << std::flush;
|
||||
}
|
||||
|
||||
if (result.has_read_error()) {
|
||||
std::cerr << "\nDownload failed: "
|
||||
<< httplib::to_string(result.read_error()) << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::cout << "\nComplete!\n";
|
||||
return 0;
|
||||
}
|
||||
@@ -243,23 +275,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;
|
||||
@@ -311,6 +349,14 @@ while (result.next()) { /* ... */ }
|
||||
auto res = cli.Get("/api/data"); // Connection can be reused
|
||||
```
|
||||
|
||||
### Payload Size Limit
|
||||
|
||||
`open_stream()` and the `stream::` helpers apply the client's `set_payload_max_length()` (100MB by default, `CPPHTTPLIB_PAYLOAD_MAX_LENGTH`) to the body, both as received and after decompression. Past the limit, `read()` and `next()` stop, and the read error is `Error::ExceedMaxPayloadSize`. To download something larger, raise the limit, or call `cli.set_payload_max_length(0)` for no limit.
|
||||
|
||||
### Authentication and Proxies
|
||||
|
||||
A stream request carries the same credentials as `client.Get()`: `set_basic_auth()` and `set_bearer_token_auth()` for the origin, and the proxy's own through `set_proxy()`, over HTTP or through a CONNECT tunnel. It does not answer a Digest challenge or follow a redirect: the `401` or `3xx` response is handed to you.
|
||||
|
||||
## Related
|
||||
|
||||
- [Issue #2269](https://github.com/yhirose/cpp-httplib/issues/2269) - Original feature request
|
||||
|
||||
+101
-24
@@ -6,7 +6,7 @@ A simple, blocking WebSocket implementation for C++11.
|
||||
> This is a blocking I/O WebSocket implementation using a thread-per-connection model (plus one heartbeat thread per connection). It is intended for small- to mid-scale workloads; handling large numbers of simultaneous WebSocket connections is outside the design target of this library. If you need high-concurrency WebSocket support with non-blocking/async I/O (e.g., thousands of simultaneous connections), this is not the one that you want.
|
||||
|
||||
> [!NOTE]
|
||||
> WebSocket extensions (`permessage-deflate` and others defined by RFC 6455) are **not supported**. If a client proposes an extension via `Sec-WebSocket-Extensions`, the server silently declines it — the negotiated connection always runs without extensions.
|
||||
> WebSocket extensions (such as `permessage-deflate`, RFC 7692) are **not supported**. If a client proposes an extension via `Sec-WebSocket-Extensions`, the server silently declines it — the negotiated connection always runs without extensions.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -57,14 +57,30 @@ if (ws.connect()) {
|
||||
|
||||
```cpp
|
||||
enum ReadResult : int {
|
||||
Fail = 0, // Connection closed or error
|
||||
Text = 1, // UTF-8 text message
|
||||
Binary = 2, // Binary message
|
||||
Fail = 0, // Connection closed or error
|
||||
Text = 1, // UTF-8 text message
|
||||
Binary = 2, // Binary message
|
||||
Timeout = 3, // Read timeout elapsed; connection still open
|
||||
};
|
||||
```
|
||||
|
||||
Returned by `read()`. Since `Fail` is `0`, the result works naturally in boolean contexts — `while (ws.read(msg))` continues until the connection closes. When you need to distinguish text from binary, check the return value directly.
|
||||
|
||||
`Timeout` is only returned for a read timeout you set yourself with `set_read_timeout()`. It means the timeout elapsed on a message boundary: nothing was consumed and the connection is still open, so you can send on it and read again. The compile-time defaults (`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`, 300 seconds on the server; a client waits forever) are a backstop against a peer that has gone quiet, not a request for control: when one of them elapses, `read()` returns `Fail` and closes the connection, so code that never calls `set_read_timeout()` can keep using `while (ws.read(msg))`.
|
||||
|
||||
**`msg` is left untouched on `Timeout`.** Because `Timeout` is non-zero, `while (ws.read(msg))` keeps looping — with the *previous* message still in `msg`. Once you set a read timeout, test the result instead:
|
||||
|
||||
```cpp
|
||||
ws.set_read_timeout(std::chrono::milliseconds(100));
|
||||
std::string msg;
|
||||
while (ws.is_open()) {
|
||||
auto r = ws.read(msg);
|
||||
if (r == httplib::ws::Timeout) { continue; } // nothing yet; send if you like
|
||||
if (r == httplib::ws::Fail) { break; }
|
||||
handle(msg);
|
||||
}
|
||||
```
|
||||
|
||||
### CloseStatus
|
||||
|
||||
```cpp
|
||||
@@ -103,14 +119,14 @@ 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)
|
||||
|
||||
Passed to the handler registered with `Server::WebSocket()`. The handler runs in a dedicated thread per connection.
|
||||
|
||||
```cpp
|
||||
// Read next message (blocks until received, returns Fail/Text/Binary)
|
||||
// Read next message (blocks until received, returns Fail/Text/Binary/Timeout)
|
||||
ReadResult read(std::string &msg);
|
||||
|
||||
// Send messages
|
||||
@@ -126,18 +142,25 @@ const Request &request() const;
|
||||
|
||||
// Check if the connection is still open
|
||||
bool is_open() const;
|
||||
|
||||
// Bound how long read() waits before returning Timeout (0 waits forever).
|
||||
// Safe to call while another thread is in read().
|
||||
void set_read_timeout(time_t sec, time_t usec = 0);
|
||||
template <class Rep, class Period>
|
||||
void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
|
||||
```
|
||||
|
||||
### WebSocketClient
|
||||
|
||||
```cpp
|
||||
// Constructor - accepts ws:// or wss:// URL
|
||||
// Constructor - accepts ws:// or wss:// URL. Any other scheme, or wss:// in a
|
||||
// build without SSL, throws std::invalid_argument (with
|
||||
// CPPHTTPLIB_NO_EXCEPTIONS, is_valid() returns false instead).
|
||||
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;
|
||||
@@ -148,15 +171,20 @@ struct PemMemory {
|
||||
explicit WebSocketClient(const std::string &scheme_host_port_path,
|
||||
const PemMemory &pem, const Headers &headers = {});
|
||||
|
||||
// Check if the URL was parsed successfully
|
||||
// Check if the URL was parsed successfully. For wss://, also false when the
|
||||
// TLS context or the client certificate cannot be loaded.
|
||||
bool is_valid() const;
|
||||
|
||||
// Connect (performs HTTP upgrade handshake). The returned Result is truthy
|
||||
// only when the handshake fully succeeded; on failure it describes what went
|
||||
// wrong:
|
||||
// res.error() httplib::Error identifying the failing layer
|
||||
// res.status() HTTP status of the upgrade response (-1 if none)
|
||||
// res.headers() headers of the upgrade response
|
||||
// res.status() HTTP status of the upgrade response (-1 if none),
|
||||
// or of the proxy's CONNECT reply when error() is
|
||||
// Error::ProxyConnection
|
||||
// res.headers() headers of that same response
|
||||
// res.get_header_value(key, def), res.has_header(key)
|
||||
// look up one of those headers
|
||||
// res.ssl_error() TLS error detail (wss://, SSL builds only)
|
||||
// res.ssl_backend_error() backend-specific TLS error code (SSL builds only)
|
||||
Result connect();
|
||||
@@ -172,6 +200,18 @@ void close(CloseStatus status = CloseStatus::Normal,
|
||||
const std::string &reason = "");
|
||||
bool is_open() const;
|
||||
|
||||
// Proxy - the same setters Client has. connect() opens a CONNECT tunnel
|
||||
// through the proxy for ws:// as well as wss:// (RFC 6455 4.1); the proxy
|
||||
// credentials are sent only on the CONNECT request, never through the tunnel.
|
||||
// Hosts matching set_no_proxy() are connected to directly.
|
||||
void set_proxy(const std::string &host, int port);
|
||||
void set_proxy_basic_auth(const std::string &username,
|
||||
const std::string &password);
|
||||
void set_proxy_bearer_token_auth(const std::string &token);
|
||||
void set_no_proxy(const std::vector<std::string> &patterns);
|
||||
void set_proxy_digest_auth(const std::string &username,
|
||||
const std::string &password); // SSL builds only
|
||||
|
||||
// Timeouts
|
||||
void set_read_timeout(time_t sec, time_t usec = 0);
|
||||
void set_write_timeout(time_t sec, time_t usec = 0);
|
||||
@@ -183,12 +223,30 @@ 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)
|
||||
// Heartbeat (see Runtime Ping Interval and Unresponsive-Peer Detection below)
|
||||
void set_websocket_ping_interval(time_t sec);
|
||||
void set_websocket_max_missed_pongs(int count);
|
||||
|
||||
// Socket - the same setters Client has
|
||||
void set_tcp_nodelay(bool on);
|
||||
void set_address_family(int family);
|
||||
void set_ipv6_v6only(bool on);
|
||||
void set_socket_options(SocketOptions socket_options);
|
||||
void set_interface(const std::string &intf);
|
||||
void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
|
||||
|
||||
// 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);
|
||||
void load_ca_cert_store(const char *ca_cert, std::size_t size);
|
||||
void enable_server_certificate_verification(bool enabled);
|
||||
void enable_server_hostname_verification(bool enabled);
|
||||
void enable_system_ca(bool enabled);
|
||||
// The same verifiers as SSLClient's, e.g. to pin the server's certificate
|
||||
void set_server_certificate_verifier(tls::VerifyCallback verifier);
|
||||
void set_session_verifier(
|
||||
std::function<SSLVerifierResponse(tls::session_t)> verifier);
|
||||
```
|
||||
|
||||
## Examples
|
||||
@@ -233,17 +291,21 @@ if (ws.connect()) {
|
||||
|
||||
`connect()` returns a `Result` that tells you why a connection attempt failed.
|
||||
`error()` distinguishes network problems (`Connection`, `ConnectionTimeout`),
|
||||
TLS problems (`SSLConnection`, `SSLServerVerification`,
|
||||
`SSLServerHostnameVerification`), and upgrade rejections
|
||||
(`WebSocketHandshake`). When the server answered with something other than
|
||||
`101 Switching Protocols`, `status()` and `headers()` carry that response:
|
||||
proxy problems (`ProxyConnection`), TLS problems (`SSLConnection`,
|
||||
`SSLServerVerification`, `SSLServerHostnameVerification`), and upgrade
|
||||
rejections (`WebSocketHandshake`). `WebSocketHandshake` covers a status other
|
||||
than `101 Switching Protocols` as well as a `101` that fails validation (for
|
||||
example a wrong `Sec-WebSocket-Accept`); either way `status()` and `headers()`
|
||||
carry the server's response. When a proxy refuses the `CONNECT` request, the
|
||||
error is `ProxyConnection` and they carry the proxy's reply instead (e.g. 407):
|
||||
|
||||
```cpp
|
||||
auto res = ws.connect();
|
||||
if (!res) {
|
||||
std::cerr << "connect failed: " << httplib::to_string(res.error()) << std::endl;
|
||||
if (res.status() != -1) {
|
||||
// The server responded but refused the upgrade (e.g. 401, 404)
|
||||
// The server refused the upgrade (e.g. 401, 404, or an invalid 101),
|
||||
// or, with ProxyConnection, the proxy refused CONNECT (e.g. 407)
|
||||
std::cerr << "HTTP status: " << res.status() << std::endl;
|
||||
}
|
||||
}
|
||||
@@ -327,6 +389,20 @@ svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws)
|
||||
});
|
||||
```
|
||||
|
||||
The check above runs after the handshake, so the client sees a successful upgrade followed by a close frame. To refuse the upgrade itself with an HTTP status, use a pre-routing or pre-request handler. Both run before the `101 Switching Protocols` response, and `req.matched_route` is available in the pre-request handler:
|
||||
|
||||
```cpp
|
||||
svr.set_pre_request_handler([](const httplib::Request &req, httplib::Response &res) {
|
||||
if (req.matched_route == "/ws" && req.get_header_value("Authorization").empty()) {
|
||||
res.status = httplib::StatusCode::Unauthorized_401;
|
||||
return httplib::Server::HandlerResponse::Handled; // not upgraded
|
||||
}
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
```
|
||||
|
||||
The server accepts a handshake from any `Origin`. A browser sends its cookies with a handshake another site starts, so if cookies authenticate the connection, also check `req.get_header_value("Origin")` against your own origins in one of these handlers (cross-site WebSocket hijacking).
|
||||
|
||||
### Custom Headers and Timeouts
|
||||
|
||||
```cpp
|
||||
@@ -408,8 +484,9 @@ if (ws.connect()) {
|
||||
|
||||
| Macro | Default | Description |
|
||||
|---------------------------------------------|-------------------|----------------------------------------------------------|
|
||||
| `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Maximum payload size per message |
|
||||
| `CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND` | `300` | Read timeout for WebSocket connections (seconds) |
|
||||
| `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Maximum payload size per message (`0` means no limit) |
|
||||
| `CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND` | `0` | Client read timeout (seconds); `0` waits forever |
|
||||
| `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` | `300` | Server read timeout (seconds) |
|
||||
| `CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND` | `5` | Timeout for waiting peer's Close response (seconds) |
|
||||
| `CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND` | `30` | Automatic Ping interval for heartbeat (seconds) |
|
||||
| `CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS` | `0` (disabled) | Close the connection after N consecutive unacked pings |
|
||||
@@ -444,13 +521,13 @@ 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. Even so, a dead connection does not linger forever: while your code is inside `read()`, `CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND` (default **300 seconds = 5 minutes**) acts as a backstop and `read()` fails if no frame arrives in time. `max_missed_pongs` is the knob for detecting an unresponsive peer faster than that 5-minute fallback.
|
||||
**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.
|
||||
|
||||
## Threading Model
|
||||
|
||||
WebSocket connections share the same thread pool as HTTP requests. Each WebSocket connection occupies one thread for its entire lifetime.
|
||||
WebSocket connections share the same thread pool as HTTP requests. Each WebSocket connection occupies one thread for its entire lifetime, so a client opening many of them can leave none for HTTP requests. Reject the upgrades you do not want in `set_pre_request_handler()`, before the connection takes a thread for good.
|
||||
|
||||
The default thread pool uses dynamic scaling: it maintains a base thread count of `CPPHTTPLIB_THREAD_POOL_COUNT` (8 or `std::thread::hardware_concurrency() - 1`, whichever is greater) and can scale up to 4x that count under load (`CPPHTTPLIB_THREAD_POOL_MAX_COUNT`). When all base threads are busy, temporary threads are spawned automatically up to the maximum. These dynamic threads exit after an idle timeout (`CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`, default 3 seconds).
|
||||
|
||||
|
||||
@@ -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,9 @@ 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()` or `set_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
|
||||
>
|
||||
> A wolfSSL server that verifies client certificates does not resume TLS sessions: wolfSSL shares its session cache between contexts, so a resumed session could carry a certificate checked against another server's client CA.
|
||||
|
||||
> [!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 +88,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
|
||||
@@ -99,12 +101,17 @@ cli.enable_server_certificate_verification(false);
|
||||
cli.enable_server_hostname_verification(false);
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The CA certificates are loaded when the client makes its first connection. Changing `set_ca_cert_path()` or `enable_system_ca()` after that has no effect, so make the settings before the first request, or use a new client. `set_ca_cert_store()` and `load_ca_cert_store()` take effect at once. `WebSocketClient` works the same way.
|
||||
|
||||
### SSL Error Handling
|
||||
|
||||
When SSL operations fail, cpp-httplib provides detailed error information through `ssl_error()` and `ssl_backend_error()`:
|
||||
|
||||
- `ssl_error()` - Returns the TLS-level error 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`. `CertVerifyFailed` comes from Mbed TLS and wolfSSL. OpenSSL checks the chain and the host name after the handshake, so a failure there leaves this `0`
|
||||
- `ssl_backend_error()` - Returns the backend-specific error code (e.g., `ERR_get_error()` for OpenSSL/wolfSSL, return value for Mbed TLS). With OpenSSL, a certificate verification failure reports the verify result (`X509_V_ERR_*`) here instead. On Windows, when CryptoAPI verifies the chain, a failure there reports the CryptoAPI error code here
|
||||
|
||||
A request that fails after the handshake with `Error::Read` or `Error::Write` also carries the TLS error behind it in both values, such as a TLS 1.3 "certificate required" alert from the server. Both values are reset for each request.
|
||||
|
||||
```c++
|
||||
#define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT
|
||||
@@ -163,11 +170,13 @@ cli.set_server_certificate_verifier(
|
||||
std::cout << "SAN: " << san.value << std::endl;
|
||||
}
|
||||
|
||||
// Return true to accept, false to reject
|
||||
// Return false to reject
|
||||
return ctx.preverify_ok;
|
||||
});
|
||||
```
|
||||
|
||||
Returning `false`, or throwing, rejects the certificate. The callback runs alongside the built-in verification, so to accept a certificate that verification rejects, such as a self-signed one, also call `enable_server_certificate_verification(false)`; the callback is then the only check.
|
||||
|
||||
### Mutual TLS (mTLS)
|
||||
|
||||
Regular TLS only verifies the server certificate. With mTLS, the client also presents a certificate that the server verifies.
|
||||
@@ -230,16 +239,20 @@ 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:
|
||||
On Windows, the CryptoAPI check can also be turned off at runtime. The TLS backend then verifies the chain instead, as on other platforms:
|
||||
|
||||
```c++
|
||||
cli.enable_windows_certificate_verification(false);
|
||||
```
|
||||
|
||||
`WebSocketClient` does not use CryptoAPI; the TLS backend always verifies its chain.
|
||||
|
||||
> [!NOTE]
|
||||
> When using SSL, it seems impossible to avoid SIGPIPE in all cases, since on some operating systems, SIGPIPE can only be suppressed on a per-message basis, but there is no way to make the OpenSSL library do so for its internal communications. If your program needs to avoid being terminated on SIGPIPE, the only fully general way might be to set up a signal handler for SIGPIPE to handle or ignore it yourself.
|
||||
>
|
||||
> On systems other than Windows, the `Server` constructor does this already: it calls `signal(SIGPIPE, SIG_IGN)`, which affects the whole process. A program that only uses clients has to do it itself.
|
||||
|
||||
## Server
|
||||
|
||||
@@ -335,11 +348,13 @@ Patterns work exactly as they do for `Get` and the other methods, so regular exp
|
||||
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.
|
||||
* `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `TRACE`, `PATCH` and `PRI` cannot be registered this way. Use `Get` (which also serves `HEAD`), `Post`, `Put`, `Delete`, `Options` or `Patch` instead. There are no handlers for `CONNECT`, `TRACE` and `PRI`; such requests get `400 Bad Request`.
|
||||
* A rejected registration makes `is_valid()` return `false`, and `listen()` then fails rather than starting a server with a route that would never fire.
|
||||
* Static file serving 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.
|
||||
|
||||
The request line and the `Host` header are read strictly, as RFC 9112 asks: a single space between the three parts of the request line, `HTTP/1.0` or `HTTP/1.1` as the version, no fragment (`#...`) in the target, and exactly one valid `Host` header (an HTTP/1.0 request may have none). Anything else gets `400 Bad Request`.
|
||||
|
||||
### Bind a socket to multiple interfaces and any available port
|
||||
|
||||
```cpp
|
||||
@@ -347,6 +362,25 @@ int port = svr.bind_to_any_port("0.0.0.0");
|
||||
svr.listen_after_bind();
|
||||
```
|
||||
|
||||
### Port sharing and exclusive binding
|
||||
|
||||
By default, the server socket enables address/port reuse: `SO_REUSEPORT` where it is available (Linux, macOS), and `SO_REUSEADDR` otherwise (Windows). A restarted server can bind again immediately, but binding to a port that another server is already listening on also succeeds, and connections are distributed between them.
|
||||
|
||||
If you want `listen()` to fail when the port is already in use, replace the default socket options with `set_socket_options`:
|
||||
|
||||
```cpp
|
||||
svr.set_socket_options([](socket_t sock) {
|
||||
#ifdef _WIN32
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1);
|
||||
#else
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
|
||||
#endif
|
||||
});
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Setting only `SO_REUSEADDR` is not enough on Windows. There, `SO_REUSEADDR` allows two sockets that both set it to bind to the same port, so use `SO_EXCLUSIVEADDRUSE` instead.
|
||||
|
||||
### Static File Server
|
||||
|
||||
```cpp
|
||||
@@ -377,6 +411,8 @@ svr.set_file_extension_and_mimetype_mapping("cpp", "text/x-c");
|
||||
svr.set_file_extension_and_mimetype_mapping("hh", "text/x-h");
|
||||
```
|
||||
|
||||
Extensions match regardless of case, so `photo.JPG` is served as `image/jpeg`. A user mapping is looked up by the exact extension first, then by the extension in lowercase.
|
||||
|
||||
The following are built-in mappings:
|
||||
|
||||
| Extension | MIME Type | Extension | MIME Type |
|
||||
@@ -419,13 +455,15 @@ svr.set_file_request_handler([](const Request &req, Response &res) {
|
||||
});
|
||||
```
|
||||
|
||||
It is not called for `HEAD` requests or `304 Not Modified` responses, so do not use it for access control; use `set_pre_routing_handler()`.
|
||||
|
||||
### Logging
|
||||
|
||||
cpp-httplib provides separate logging capabilities for access logs and error logs, similar to web servers like Nginx and Apache.
|
||||
|
||||
#### Access Logging
|
||||
|
||||
Access loggers capture successful HTTP requests and responses:
|
||||
Access loggers capture each request and the response written for it, including the error responses the library writes itself, such as `400`, `404`, `413` or `500`:
|
||||
|
||||
```cpp
|
||||
svr.set_logger([](const httplib::Request& req, const httplib::Response& res) {
|
||||
@@ -433,6 +471,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:
|
||||
@@ -445,7 +486,7 @@ svr.set_pre_compression_logger([](const httplib::Request& req, const httplib::Re
|
||||
});
|
||||
```
|
||||
|
||||
The pre-compression logger is only called when compression would be applied. For responses without compression, only the access logger is called.
|
||||
The pre-compression logger is only called when the server compresses `res.body` or a static file. It is not called for a response without compression, nor for a chunked content provider, whose body is compressed as it is written; for those, only the access logger is called.
|
||||
|
||||
For a static file response (see [Static file compression](#static-file-compression)), `res.body` is empty when the logger runs. The bytes are still on disk at that point, not in memory.
|
||||
|
||||
@@ -477,7 +518,7 @@ svr.set_error_handler([](const auto& req, auto& res) {
|
||||
```
|
||||
|
||||
### Exception handler
|
||||
The exception handler gets called if a user routing handler throws an error.
|
||||
The exception handler gets called if a user routing handler throws an error. This covers the pre-routing handler, the file request handler, the pre-request handler, route handlers and content readers. An exception from the post-routing handler, the error handler, the `Expect: 100-continue` handler, a content provider, a logger or a WebSocket handler does not reach it: the connection is dropped, and the error logger receives `Error::UserCallbackException`.
|
||||
|
||||
```cpp
|
||||
svr.set_exception_handler([](const auto& req, auto& res, std::exception_ptr ep) {
|
||||
@@ -496,7 +537,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
|
||||
|
||||
@@ -545,28 +586,34 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
|
||||
|
||||
```
|
||||
Request received
|
||||
│
|
||||
├─ pre_routing_handler route not matched yet, body not read
|
||||
│ └─ returns Handled → stop here
|
||||
│
|
||||
├─ file_request_handler (GET/HEAD, static file serving)
|
||||
│
|
||||
├─ expect_100_continue_handler (when the request has "Expect: 100-continue")
|
||||
│ └─ returns a status other than 100 → go straight to post_routing_handler
|
||||
│
|
||||
├─ pre_routing_handler route not matched yet, body not read
|
||||
│ └─ returns Handled → go straight to post_routing_handler
|
||||
│
|
||||
├─ file_request_handler when a static file is served (GET only)
|
||||
│ └─ a mount point answered → go straight to post_routing_handler
|
||||
│
|
||||
├─ route matching → req.matched_route is set
|
||||
│
|
||||
├─ pre_request_handler route matched, body NOT read yet
|
||||
│ └─ returns Handled → 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
|
||||
```
|
||||
|
||||
Use `pre_routing_handler` to reject a request as early as possible, before the route is known. Use `pre_request_handler` for route-specific checks, since `req.matched_route` is available and the body has not been read yet.
|
||||
Use `pre_routing_handler` to reject a request as early as possible, before the route is known. Use `pre_request_handler` for route-specific checks, since `req.matched_route` is available and the body has not been read yet. A request that a mount point answers never reaches route matching or `pre_request_handler`, so reject such a request in `pre_routing_handler`.
|
||||
|
||||
For a request with `Expect: 100-continue`, the `100 Continue` response is not sent until the body is about to be read. A request rejected before that point (by `pre_routing_handler`, `pre_request_handler`, or because no route matched) gets its final response without `100 Continue`, so the client never sends the body.
|
||||
|
||||
A WebSocket upgrade request that matches a route registered with `svr.WebSocket()` takes a shorter path: `pre_routing_handler`, then route matching (`req.matched_route` is set), then `pre_request_handler`, then the WebSocket handler. If either hook returns `Handled`, its response is sent as a regular HTTP response and the connection is not upgraded. Once the connection is upgraded, `post_routing_handler` does not run.
|
||||
|
||||
### Response user data
|
||||
|
||||
@@ -584,7 +631,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;
|
||||
@@ -688,7 +735,10 @@ svr.Post("/multipart", [&](const Request& req, Response& res) {
|
||||
auto safe = httplib::sanitize_filename(file.filename);
|
||||
```
|
||||
|
||||
This function strips path separators (`/`, `\`), null bytes, leading/trailing whitespace, and rejects `.` and `..`. Returns an empty string if the filename is unsafe.
|
||||
This function keeps only the part after the last `/` or `\`, removes null bytes, and trims leading and trailing spaces and tabs. It returns an empty string if what is left is empty, `.` or `..`.
|
||||
|
||||
> [!NOTE]
|
||||
> `name` and `filename` are read as quoted-strings (RFC 9110 §5.6.4), where `\"` and `\\` stand for `"` and `\`. Browsers send a backslash as it is, so from a browser, a value with `\\` in it arrives with a single `\`, and one that ends in `\` is not read correctly.
|
||||
|
||||
### Receive content with a content receiver
|
||||
|
||||
@@ -730,11 +780,17 @@ svr.Post("/content_receiver",
|
||||
});
|
||||
```
|
||||
|
||||
`CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT` (default 1024) caps the number of
|
||||
form-data parts only on the buffered path, where every part is accumulated into
|
||||
`req.form`. The content receiver keeps nothing, so the cap does not apply here.
|
||||
If your handler needs an upper bound on the number of parts, count them yourself
|
||||
and return `false` from the callback to stop the parser.
|
||||
`content_reader` reads the body once per request; a second call returns `false`.
|
||||
When a callback returns `false`, reading stops, `content_reader` returns `false`,
|
||||
and `res.status` is set to `400` unless the handler sets another status. The
|
||||
rest of the body is left unread, so the connection is closed after the response.
|
||||
|
||||
`CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT` (default 1024, `0` for no limit)
|
||||
caps the number of form-data parts only on the buffered path, where every part
|
||||
is accumulated into `req.form`. The content receiver keeps nothing, so the cap
|
||||
does not apply here. If your handler needs an upper bound on the number of
|
||||
parts, count them yourself and return `false` from the callback to stop the
|
||||
parser.
|
||||
|
||||
### Send content with the content provider
|
||||
|
||||
@@ -756,6 +812,8 @@ svr.Get("/stream", [&](const Request &req, Response &res) {
|
||||
});
|
||||
```
|
||||
|
||||
Write at most `length` bytes per call. Anything past it is not sent, and the response fails. The response also fails if a call returns `true` without writing anything, or if `sink.done()` is called before the whole content length is written.
|
||||
|
||||
Without content length:
|
||||
|
||||
```cpp
|
||||
@@ -775,6 +833,8 @@ svr.Get("/stream", [&](const Request &req, Response &res) {
|
||||
});
|
||||
```
|
||||
|
||||
Such a body ends where the connection does, so the server sends `Connection: close` and closes the connection after the response. Use `set_chunked_content_provider()` to keep the connection open.
|
||||
|
||||
### Chunked transfer encoding
|
||||
|
||||
```cpp
|
||||
@@ -827,7 +887,9 @@ svr.Get("/content", [&](const Request &req, Response &res) {
|
||||
|
||||
### 'Expect: 100-continue' handler
|
||||
|
||||
By default, the server sends a `100 Continue` response for an `Expect: 100-continue` header.
|
||||
By default, the server accepts an `Expect: 100-continue` header and sends a `100 Continue` response when it starts reading the request body. If the request is answered without reading the body, `100 Continue` is not sent and the connection is closed after the response.
|
||||
|
||||
The handler runs before `pre_routing_handler`. Returning `100` lets the request proceed; returning any other status sends that status as the final response and closes the connection.
|
||||
|
||||
```cpp
|
||||
// Send a '417 Expectation Failed' response.
|
||||
@@ -846,7 +908,7 @@ svr.set_expect_100_continue_handler([](const Request &req, Response &res) {
|
||||
### Keep-Alive connection
|
||||
|
||||
```cpp
|
||||
svr.set_keep_alive_max_count(2); // Default is 100
|
||||
svr.set_keep_alive_max_count(2); // Default is 100, 0 for no limit
|
||||
svr.set_keep_alive_timeout(10); // Default is 5
|
||||
```
|
||||
|
||||
@@ -862,14 +924,18 @@ svr.set_read_timeout(std::chrono::seconds(5));
|
||||
svr.set_keep_alive_timeout(std::chrono::seconds(10));
|
||||
```
|
||||
|
||||
The read timeout bounds the request line and headers as a whole, and each read of a request body.
|
||||
|
||||
### Set maximum payload length for reading a request body
|
||||
|
||||
```c++
|
||||
svr.set_payload_max_length(1024 * 1024 * 512); // 512MB
|
||||
```
|
||||
|
||||
The default is `CPPHTTPLIB_PAYLOAD_MAX_LENGTH` (100MB), and `0` means no limit. A request with a larger body gets `413 Payload Too Large`.
|
||||
|
||||
> [!NOTE]
|
||||
> When the request body content type is 'www-form-urlencoded', the actual payload length shouldn't exceed `CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH`.
|
||||
> When the request body content type is `application/x-www-form-urlencoded`, the body must not exceed `CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH` (8192 bytes by default, `0` for no limit). A larger one gets `413 Payload Too Large`.
|
||||
|
||||
### Server-Sent Events
|
||||
|
||||
@@ -879,7 +945,9 @@ 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 a new task arrives and the queued tasks outnumber the idle threads, a temporary thread is spawned (up to the maximum). A dynamic thread exits automatically once it has waited for the idle timeout without receiving a task. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`.
|
||||
|
||||
A connection holds its thread while it is served: between requests up to the keep-alive timeout, through a request body sent slowly but within the read timeout, and for the whole life of a WebSocket. Enough of them leave no thread for anyone else, so in front of untrusted clients, put a reverse proxy that limits connections per client, and reject unwanted WebSocket upgrades in the pre-request handler.
|
||||
|
||||
If you want to set the thread counts at runtime:
|
||||
|
||||
@@ -950,7 +1018,7 @@ int main(void)
|
||||
httplib::Client cli("localhost", 1234);
|
||||
|
||||
if (auto res = cli.Get("/hi")) {
|
||||
if (res->status == StatusCode::OK_200) {
|
||||
if (res->status == httplib::StatusCode::OK_200) {
|
||||
std::cout << res->body << std::endl;
|
||||
}
|
||||
} else {
|
||||
@@ -1013,6 +1081,8 @@ enum class Error {
|
||||
HTTPParsing,
|
||||
InvalidRangeHeader,
|
||||
UnsupportedContentEncoding,
|
||||
WebSocketHandshake,
|
||||
UserCallbackException,
|
||||
};
|
||||
```
|
||||
|
||||
@@ -1061,6 +1131,8 @@ cli.set_error_logger([](const httplib::Error& err, const httplib::Request* req)
|
||||
});
|
||||
```
|
||||
|
||||
Each failed request is reported once, with the request you made, also when it failed on a redirect or was a stream that failed to open (`open_stream()`, `stream::Get()`).
|
||||
|
||||
### GET with HTTP headers
|
||||
|
||||
```c++
|
||||
@@ -1085,6 +1157,8 @@ cli.set_default_headers({
|
||||
auto res = cli.Get("/hi");
|
||||
```
|
||||
|
||||
A `Content-Length` among these headers is sent in place of the one the library would send, so it has to match the body as written. A `Transfer-Encoding` is sent in addition to the library's own framing, so leave it out. Leave both out when passing on the headers of another message, as a proxy does.
|
||||
|
||||
### POST
|
||||
|
||||
```c++
|
||||
@@ -1178,7 +1252,7 @@ cli.set_connection_timeout(0, 300000); // 300 milliseconds
|
||||
cli.set_read_timeout(5, 0); // 5 seconds
|
||||
cli.set_write_timeout(5, 0); // 5 seconds
|
||||
|
||||
// This method works the same as curl's `--max-time` option
|
||||
// A deadline for the whole request (see below)
|
||||
cli.set_max_timeout(5000); // 5 seconds
|
||||
|
||||
// std::chrono is also supported
|
||||
@@ -1188,12 +1262,16 @@ cli.set_write_timeout(std::chrono::seconds(5));
|
||||
cli.set_max_timeout(std::chrono::seconds(5));
|
||||
```
|
||||
|
||||
`set_max_timeout()` is similar to curl's `--max-time` option, but the deadline only shortens the waits for reading the response. Connecting and writing are bounded by the connection and write timeouts.
|
||||
|
||||
### Set maximum payload length for reading a response body
|
||||
|
||||
```c++
|
||||
cli.set_payload_max_length(1024 * 1024 * 512); // 512MB
|
||||
```
|
||||
|
||||
A response body over the limit, also once decompressed, fails the request with `Error::ExceedMaxPayloadSize`.
|
||||
|
||||
### Receive content with a content receiver
|
||||
|
||||
```c++
|
||||
@@ -1212,8 +1290,8 @@ std::string body;
|
||||
auto res = cli.Get(
|
||||
"/stream", Headers(),
|
||||
[&](const Response &response) {
|
||||
EXPECT_EQ(StatusCode::OK_200, response.status);
|
||||
return true; // return 'false' if you want to cancel the request.
|
||||
// return 'false' if you want to cancel the request.
|
||||
return response.status == StatusCode::OK_200;
|
||||
},
|
||||
[&](const char *data, size_t data_length) {
|
||||
body.append(data, data_length);
|
||||
@@ -1228,13 +1306,15 @@ 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.
|
||||
},
|
||||
"text/plain");
|
||||
```
|
||||
|
||||
As on the server, write at most `length` bytes per call. The request fails with `Error::Write` if a call writes more, returns `true` without writing anything, or calls `sink.done()` before the whole content length is written.
|
||||
|
||||
### Chunked transfer encoding
|
||||
|
||||
```cpp
|
||||
@@ -1281,7 +1361,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
|
||||
|
||||
@@ -1299,12 +1379,14 @@ 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.
|
||||
|
||||
When the proxy refuses the `CONNECT` of an HTTPS request, the request fails with `Error::ProxyConnection`. Only a `407 Proxy Authentication Required` comes back as the response, since any other answer from the proxy could be taken for the origin's.
|
||||
|
||||
#### Bypass the proxy for specific hosts (`NO_PROXY`)
|
||||
|
||||
```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.
|
||||
@@ -1312,6 +1394,10 @@ Hostname matching is case-insensitive with a dot-boundary rule. See the
|
||||
[NO_PROXY cookbook](https://yhirose.github.io/cpp-httplib/en/cookbook/c16-proxy)
|
||||
for details and for reading the variable from the environment.
|
||||
|
||||
`set_proxy()`, `set_proxy_basic_auth()`, `set_proxy_bearer_token_auth()`,
|
||||
`set_proxy_digest_auth()` and `set_no_proxy()` are also available on
|
||||
`httplib::ws::WebSocketClient`.
|
||||
|
||||
### Range
|
||||
|
||||
```cpp
|
||||
@@ -1357,10 +1443,16 @@ res = cli.Get("/");
|
||||
res->status; // 200
|
||||
```
|
||||
|
||||
A URL with userinfo (`http://user:pass@host/`) is not supported, neither for a `Client` nor in a `Location`; use `set_basic_auth()` for the credentials. A `Client` constructed from a URL it cannot use, such as one with userinfo, a backslash in the authority or an invalid port, is not valid: `is_valid()` returns `false`, and every request fails with `Error::Connection`.
|
||||
|
||||
On a redirect to another origin (a different scheme, host or port), `Authorization`, `Cookie` and `Proxy-Authorization` are dropped along with the credentials set with `set_basic_auth()`, `set_bearer_token_auth()` and `set_digest_auth()`, and the client certificate is not presented. Other headers, the default ones included, go along (RFC 9110 §15.4), and so do the timeouts, the payload limit and the TLS verification settings. A `303` that turns a request into a `GET` drops its headers and body; only on the same origin are the default headers sent again.
|
||||
|
||||
Up to `CPPHTTPLIB_REDIRECT_MAX_COUNT` (20 by default) redirects are followed for a request; one more fails it with `Error::ExceedRedirectCount`. Interim `1xx` responses before the final response are skipped, up to `CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT` (100 by default); one more fails the request with `Error::Read`.
|
||||
|
||||
### Use a specific network interface
|
||||
|
||||
> [!NOTE]
|
||||
> This feature is not available on Windows, yet.
|
||||
> This feature is not available on Windows, Android, AIX and z/OS. The setting is ignored there.
|
||||
|
||||
```cpp
|
||||
cli.set_interface("eth0"); // Interface name, IP address or host name
|
||||
@@ -1409,13 +1501,15 @@ auto res = cli.Get("/path with spaces/file.txt"); // Automatically encodes space
|
||||
|
||||
// Disable automatic path encoding
|
||||
cli.set_path_encode(false);
|
||||
auto res = cli.Get("/already%20encoded/path"); // Use pre-encoded paths
|
||||
res = cli.Get("/already%20encoded/path"); // Use pre-encoded paths
|
||||
```
|
||||
|
||||
- `set_path_encode(bool on)` - Controls automatic encoding of special characters in URL paths
|
||||
- `true` (default): Automatically encodes spaces, plus signs, newlines, and other special characters
|
||||
- `false`: Sends paths as-is without encoding (useful for pre-encoded URLs)
|
||||
|
||||
A fragment (`#...`) in the path is never sent, whatever the setting.
|
||||
|
||||
### Performance Note for Local Connections
|
||||
|
||||
> [!WARNING]
|
||||
@@ -1449,8 +1543,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.
|
||||
@@ -1460,7 +1554,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. The [Stream API](#stream-api) is limited either way.
|
||||
|
||||
## Compression
|
||||
|
||||
@@ -1469,10 +1563,28 @@ 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:
|
||||
|
||||
```c++
|
||||
svr.Get("/app.js", [](const Request & /*req*/, Response &res) {
|
||||
res.set_header("Content-Encoding", "gzip");
|
||||
res.set_content(gzipped_asset, "application/javascript");
|
||||
});
|
||||
```
|
||||
|
||||
This holds for every kind of response, including the file-backed ones below.
|
||||
|
||||
`Vary: Accept-Encoding` is added only to responses the server encoded itself. A handler that chooses between an encoded and an identity representation by reading `Accept-Encoding` should set the field itself, so that shared caches keep the two apart.
|
||||
|
||||
### Static file compression
|
||||
|
||||
@@ -1516,14 +1628,14 @@ Please see https://github.com/facebook/zstd for more detail.
|
||||
|
||||
### Default `Accept-Encoding` value
|
||||
|
||||
The default `Accept-Encoding` value contains all possible compression types. So, the following two examples are same.
|
||||
The default `Accept-Encoding` value lists the compression types the library is built with. It is not added to a request made with a content receiver. So, with Brotli, zlib and Zstd support all enabled, the following two examples are the same.
|
||||
|
||||
```c++
|
||||
res = cli.Get("/resource/foo");
|
||||
res = cli.Get("/resource/foo", httplib::Headers{{"Accept-Encoding", "br, gzip, deflate, zstd"}});
|
||||
```
|
||||
|
||||
If we don't want a response without compression, we have to set `Accept-Encoding` to an empty string. This behavior is similar to curl.
|
||||
If we want a response without compression, we have to set `Accept-Encoding` to an empty string. This behavior is similar to curl.
|
||||
|
||||
```c++
|
||||
res = cli.Get("/resource/foo", httplib::Headers{{"Accept-Encoding", ""}});
|
||||
@@ -1536,7 +1648,7 @@ cli.set_compress(true);
|
||||
res = cli.Post("/resource/foo", "...", "text/plain");
|
||||
```
|
||||
|
||||
### Compress response body on client
|
||||
### Keep response body compressed on client
|
||||
|
||||
```c++
|
||||
cli.set_decompress(false);
|
||||
@@ -1561,7 +1673,7 @@ cli.set_address_family(AF_UNIX);
|
||||
|
||||
"my-socket.sock" can be a relative path or an absolute path. Your application must have the appropriate permissions for the path. You can also use an abstract socket address on Linux. To use an abstract socket address, prepend a null byte ('\x00') to the path.
|
||||
|
||||
This library automatically sets the Host header to "localhost" for Unix socket connections, similar to curl's behavior:
|
||||
This library automatically sets the Host header to "localhost" for Unix socket connections, similar to curl's behavior.
|
||||
|
||||
|
||||
URI Encoding/Decoding Utilities
|
||||
@@ -1584,8 +1696,8 @@ std::string decoded_component = httplib::decode_uri_component(encoded_component)
|
||||
### Functions
|
||||
|
||||
- `encode_uri(const std::string &value)` - Encodes a full URI, preserving reserved characters like `://`, `?`, `&`, `=`
|
||||
- `decode_uri(const std::string &value)` - Decodes a URI-encoded string
|
||||
- `encode_uri_component(const std::string &value)` - Encodes a URI component (query parameter, path segment), encoding all reserved characters
|
||||
- `decode_uri(const std::string &value)` - Decodes a URI-encoded string, but leaves escapes of the reserved characters that `encode_uri()` preserves (e.g. `%2F`, `%3F`) as they are, like JavaScript's `decodeURI()`
|
||||
- `encode_uri_component(const std::string &value)` - Encodes a URI component (query parameter, path segment), encoding all reserved characters except `!`, `*`, `'`, `(` and `)`, like JavaScript's `encodeURIComponent()`
|
||||
- `decode_uri_component(const std::string &value)` - Decodes a URI component
|
||||
|
||||
Use `encode_uri()` for full URLs and `encode_uri_component()` for individual query parameters or path segments.
|
||||
@@ -1596,7 +1708,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");
|
||||
@@ -1615,6 +1726,8 @@ if (result2) {
|
||||
|
||||
All HTTP methods are supported: `stream::Get`, `Post`, `Put`, `Patch`, `Delete`, `Head`, `Options`.
|
||||
|
||||
Unlike a content receiver, the Stream API is bounded by the client's `set_payload_max_length()` (100MB by default). Reading past it stops with `read_error() == Error::ExceedMaxPayloadSize`.
|
||||
|
||||
See [README-stream.md](README-stream.md) for more details.
|
||||
|
||||
## SSE Client
|
||||
@@ -1676,7 +1789,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.
|
||||
|
||||
@@ -1685,12 +1798,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
|
||||
|
||||
@@ -1719,7 +1834,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 ..."
|
||||
@@ -1729,7 +1846,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 ..."
|
||||
@@ -1741,20 +1860,16 @@ 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
|
||||
> ```
|
||||
>
|
||||
> The limit is no guarantee on a thread with a small stack, such as one of musl's 128KB threads, where a pattern like `(\w|-)+` can already overflow on a shorter path; lower the limit there. Nor does it bound the time a pattern with nested repetition, such as `((\w+-?)+)`, can take to fail on a few dozen characters. Keep regex routes simple.
|
||||
|
||||
### 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.54.0"
|
||||
version = "0.62.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
|
||||
|
||||
|
||||
@@ -50,6 +50,6 @@ httplib::Headers headers = {
|
||||
auto res = cli.Get("/users", headers);
|
||||
```
|
||||
|
||||
Per-request headers are **added** on top of the defaults. Both are sent to the server.
|
||||
Per-request headers are **added** on top of the defaults, and both are sent to the server. If a per-request header has the same name as a default one, only the per-request one is sent.
|
||||
|
||||
> For details on Bearer token auth, see [C06. Call an API with a Bearer token](../c06-bearer-token).
|
||||
@@ -33,6 +33,8 @@ auto res = cli.Get("/");
|
||||
|
||||
Many sites redirect HTTP traffic to HTTPS. With `set_follow_location(true)` on, this case is handled transparently — the client follows redirects even when the scheme or host changes.
|
||||
|
||||
When a redirect goes to another origin (a different scheme, host, or port), the client drops the `Authorization`, `Cookie`, and `Proxy-Authorization` headers, along with the credentials set with `set_basic_auth()` and the like, and doesn't present the client certificate. Other headers, default ones included, go along, and so do the timeouts, the payload limit, and the TLS verification settings.
|
||||
|
||||
> **Warning:** To follow redirects to HTTPS, you need to build cpp-httplib with OpenSSL (or another TLS backend). Without TLS support, redirects to HTTPS will fail.
|
||||
|
||||
> **Note:** Following redirects adds to the total request time. See [C12. Set timeouts](../c12-timeouts) for timeout configuration.
|
||||
@@ -12,7 +12,7 @@ Sometimes you want to send a file's contents as the request body directly — no
|
||||
httplib::Client cli("https://storage.example.com");
|
||||
|
||||
auto [size, provider] = httplib::make_file_body("backup.tar.gz");
|
||||
if (size == 0) {
|
||||
if (!provider) {
|
||||
std::cerr << "Failed to open file" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ The `ContentProvider` reads the file in chunks, so even huge files never sit ful
|
||||
|
||||
## When the file can't be opened
|
||||
|
||||
If the file can't be opened, `make_file_body()` returns `size` as `0` and `provider` as an empty function object. Sending that would produce garbage — always check `size` first.
|
||||
If the file can't be opened, `make_file_body()` returns `size` as `0` and `provider` as an empty function object. Sending that would upload an empty body — always check `provider` first. Checking `size` won't do: an empty file also gives `0`, with a working `provider`.
|
||||
|
||||
> **Warning:** `make_file_body()` needs to fix the Content-Length up front, so it reads the file size ahead of time. If the file size might change mid-upload, this API isn't the right fit.
|
||||
|
||||
|
||||
@@ -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).
|
||||
@@ -12,6 +12,8 @@ The client has three kinds of timeouts, each set independently.
|
||||
| Read | `set_read_timeout` | 300s | Time to wait for a single `recv` when receiving the response |
|
||||
| Write | `set_write_timeout` | 5s | Time to wait for a single `send` when sending the request |
|
||||
|
||||
Over HTTPS, the connection timeout also bounds the whole TLS handshake. A handshake that doesn't finish in time fails with `Error::SSLConnection`.
|
||||
|
||||
## Basic usage
|
||||
|
||||
```cpp
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 13
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
The three timeouts from [C12. Set timeouts](../c12-timeouts) all apply to a single `send` or `recv` call. To cap the total time a request can take, use `set_max_timeout()`.
|
||||
The three timeouts from [C12. Set timeouts](../c12-timeouts) each cover only one step: the read and write timeouts apply to a single `recv` or `send` call, and the connection timeout to connecting. To cap the total time a request can take, use `set_max_timeout()`.
|
||||
|
||||
## Basic usage
|
||||
|
||||
@@ -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, PUT, or PATCH 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.
|
||||
@@ -17,6 +17,8 @@ auto res = cli.Get("/users");
|
||||
|
||||
The request goes through the proxy. For HTTPS, the client uses the CONNECT method to tunnel through — no extra setup required.
|
||||
|
||||
If the proxy refuses the tunnel, the request fails with `Error::ProxyConnection`. The exception is a 407: it comes back as the response, so `res` is truthy and `res->status` is 407, while `res.error()` still returns `Error::ProxyConnection`.
|
||||
|
||||
## Proxy authentication
|
||||
|
||||
If the proxy itself requires authentication, use `set_proxy_basic_auth()` or `set_proxy_bearer_token_auth()`.
|
||||
@@ -55,7 +57,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:
|
||||
@@ -69,6 +71,20 @@ Hostname matching is case-insensitive and uses a dot-boundary rule, so an entry
|
||||
|
||||
Malformed entries are silently dropped. Port-specific entries such as `example.com:8080` are not supported (cpp-httplib's other host-keyed APIs are also keyed on hostname only).
|
||||
|
||||
## Use a proxy for WebSocket
|
||||
|
||||
`ws::WebSocketClient` has the same proxy setters.
|
||||
|
||||
```cpp
|
||||
httplib::ws::WebSocketClient cli("wss://ws.example.com/chat");
|
||||
cli.set_proxy("proxy.internal", 8080);
|
||||
cli.set_proxy_basic_auth("user", "password");
|
||||
|
||||
auto res = cli.connect();
|
||||
```
|
||||
|
||||
For both `ws://` and `wss://`, the client opens a tunnel with the CONNECT method and then performs the WebSocket handshake through it. `set_no_proxy()` works the same way.
|
||||
|
||||
## Read proxy settings from the environment
|
||||
|
||||
cpp-httplib doesn't touch `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` on its own — the config API is always explicit, the same way `set_ca_cert_path()` is. If you'd like that behavior, read the variables in your application and feed them to `set_proxy()` and `set_no_proxy()`.
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 17
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
`cli.Get()`, `cli.Post()`, and friends return a `Result`. When the request fails — can't reach the server, times out, etc. — the result is "falsy". To get the specific reason, use `Result::error()`.
|
||||
`cli.Get()`, `cli.Post()`, and friends return a `Result`. When the request fails — can't reach the server, times out, etc. — the result is "falsy", with one exception noted in the table below. To get the specific reason, use `Result::error()`.
|
||||
|
||||
## Basic check
|
||||
|
||||
@@ -27,14 +27,16 @@ Use `if (res)` to check success. On failure, `res.error()` returns a `httplib::E
|
||||
|
||||
| Value | Meaning |
|
||||
| --- | --- |
|
||||
| `Error::Connection` | Couldn't connect to the server |
|
||||
| `Error::Connection` | Couldn't connect to the server, or the `Client` was built from a URL it can't use (userinfo or a backslash in the authority, a bad port). In the latter case `cli.is_valid()` is `false` |
|
||||
| `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::ExceedMaxPayloadSize` | The response body is larger than `set_payload_max_length()` allows, also once decompressed |
|
||||
| `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 |
|
||||
| `Error::Canceled` | A progress callback returned `false` |
|
||||
| `Error::ProxyConnection` | The proxy refused the CONNECT tunnel. A 407 is the exception: `res` is truthy with `res->status == 407`, and `res.error()` is still `Error::ProxyConnection` |
|
||||
| `Error::Canceled` | A progress callback, a `ContentReceiver`, a `ResponseHandler`, or an upload content provider returned `false` |
|
||||
|
||||
## Network errors vs. HTTP errors
|
||||
|
||||
|
||||
@@ -17,26 +17,34 @@ if (!res) {
|
||||
std::cerr << "error: " << httplib::to_string(err) << std::endl;
|
||||
|
||||
if (err == httplib::Error::SSLConnection ||
|
||||
err == httplib::Error::SSLServerVerification) {
|
||||
err == httplib::Error::SSLServerVerification ||
|
||||
err == httplib::Error::Read || err == httplib::Error::Write) {
|
||||
std::cerr << "ssl_error: " << res.ssl_error() << std::endl;
|
||||
std::cerr << "ssl_backend_error: " << res.ssl_backend_error() << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`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 or a later read or write failed, and the verify result (`X509_V_ERR_*`) when certificate verification failed.
|
||||
|
||||
A request that fails after the handshake reports `Error::Read` or `Error::Write`. Even then, `ssl_error()` and `ssl_backend_error()` carry the TLS error behind it. For example, if the server requires a client certificate you didn't send, OpenSSL's error reads "tlsv13 alert certificate required". Both values are reset for each request and are `0` when no TLS error was involved.
|
||||
|
||||
## 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;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ cli.set_error_logger([](const httplib::Error &err, const httplib::Request *req)
|
||||
});
|
||||
```
|
||||
|
||||
The second argument `req` can be null — it happens when the failure occurred before the request was built. Always null-check before dereferencing.
|
||||
Each failed request is reported once, with the request you made, also when it failed on a redirect. A stream that fails to open with `open_stream()` or `stream::Get()` is reported the same way; errors while reading its body come back through `read_error()` instead. `req` is null only in a server's error logger, for errors that belong to no request.
|
||||
|
||||
## Use both together
|
||||
|
||||
|
||||
@@ -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,9 @@ 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. It stops after a 204, 403, or 404 response, or once the attempts set with `set_max_reconnect_attempts()` run out.
|
||||
|
||||
It also stops when an event, or a line still waiting for its end, grows past `CPPHTTPLIB_SSE_MAX_EVENT_LENGTH` (16MB by default, 0 for no limit). The error handler then gets `Error::ExceedMaxPayloadSize`. The client's `set_payload_max_length()` doesn't apply to the stream as a whole, since an event stream has no end.
|
||||
|
||||
## Run asynchronously
|
||||
|
||||
@@ -88,6 +90,8 @@ If the server sends a `retry:` field, that takes precedence.
|
||||
|
||||
`SSEClient` tracks the `id` of each received event internally and sends it back as `Last-Event-ID` on reconnect. As long as the server sends events with `id:`, this all works automatically.
|
||||
|
||||
An empty `id:` clears the stored id. An `id:` that can't be sent as a header value (one with NUL or other control characters, or with leading or trailing whitespace) is ignored, and the previous id stays.
|
||||
|
||||
```cpp
|
||||
std::cout << "last id: " << sse.last_event_id() << std::endl;
|
||||
```
|
||||
|
||||
@@ -44,6 +44,8 @@ svr.Get(R"(/users/(\d+))", [](const httplib::Request &req, httplib::Response &re
|
||||
|
||||
Parentheses in the pattern become captures in `req.matches`. `req.matches[0]` is the full match; `req.matches[1]` onward are the captures.
|
||||
|
||||
A regex route isn't applied to a path longer than `CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH` (256 by default); such a path is treated as no match. This keeps `std::regex` from overflowing the stack on long input. If your routes need longer paths, define the macro with a larger value.
|
||||
|
||||
## Which to use
|
||||
|
||||
- For plain IDs or slugs, `:name` is enough — readable, and the shape is obvious
|
||||
|
||||
@@ -10,12 +10,19 @@ To serve static files like HTML, CSS, and images, use `set_mount_point()`. Just
|
||||
|
||||
```cpp
|
||||
httplib::Server svr;
|
||||
svr.set_mount_point("/", "./public");
|
||||
if (!svr.set_mount_point("/", "./public")) {
|
||||
// ./public doesn't exist
|
||||
return 1;
|
||||
}
|
||||
svr.listen("0.0.0.0", 8080);
|
||||
```
|
||||
|
||||
`set_mount_point()` returns `false` when the directory doesn't exist, so check the return value.
|
||||
|
||||
`./public/index.html` is now reachable at `http://localhost:8080/index.html`, and `./public/css/style.css` at `http://localhost:8080/css/style.css`. The directory layout maps directly to URLs.
|
||||
|
||||
A request for a directory serves its `index.html`, and one without the trailing slash (`/docs`) is redirected (301) to `/docs/`. A symlink that resolves outside the mounted directory gets a 403.
|
||||
|
||||
## Multiple mount points
|
||||
|
||||
You can register more than one mount point.
|
||||
@@ -30,7 +37,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
|
||||
|
||||
|
||||
@@ -48,22 +48,30 @@ svr.Post("/upload",
|
||||
const httplib::ContentReader &content_reader) {
|
||||
std::ofstream ofs;
|
||||
|
||||
content_reader(
|
||||
auto ok = content_reader(
|
||||
[&](const httplib::FormData &file) {
|
||||
if (!file.filename.empty()) {
|
||||
ofs.open("uploads/" + file.filename, std::ios::binary);
|
||||
}
|
||||
return static_cast<bool>(ofs);
|
||||
if (ofs.is_open()) { ofs.close(); } // done with the previous file
|
||||
if (file.filename.empty()) { return true; } // a plain field, skip it
|
||||
|
||||
auto name = httplib::sanitize_filename(file.filename);
|
||||
if (name.empty()) { return false; } // reject an unsafe name
|
||||
|
||||
ofs.open("uploads/" + name, std::ios::binary);
|
||||
return ofs.is_open();
|
||||
},
|
||||
[&](const char *data, size_t len) {
|
||||
if (!ofs.is_open()) { return true; } // not part of a file
|
||||
ofs.write(data, len);
|
||||
return static_cast<bool>(ofs);
|
||||
});
|
||||
|
||||
if (!ok) { return; } // the status is already set
|
||||
res.set_content("uploaded", "text/plain");
|
||||
});
|
||||
```
|
||||
|
||||
The header callback runs at the start of every part, so it closes the previous file before opening the next one. `file.filename` is whatever the client sent, so always pass it through `httplib::sanitize_filename()`. An empty result means the name is unsafe.
|
||||
|
||||
Only a small chunk sits in memory at any moment, so gigabyte-scale files are no problem.
|
||||
|
||||
## Count the parts yourself
|
||||
@@ -96,7 +104,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
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ svr.set_pre_routing_handler(
|
||||
});
|
||||
```
|
||||
|
||||
The pre-routing handler runs **before routing**. It catches every request — including ones that don't match any handler.
|
||||
The pre-routing handler runs **before routing**. It catches every request — including ones that don't match any handler. The exception is a request rejected while its request line and headers are parsed (400 for a malformed request, 414 for an overlong URI, 416 for a malformed `Range`); the server answers those before this handler runs.
|
||||
|
||||
The `HandlerResponse` return value is key:
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ svr.Options("/.*", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`/.*` is a regex route, so it isn't applied to paths longer than `CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH` (256 by default). If your paths can be longer, handle `OPTIONS` in the pre-routing handler instead.
|
||||
|
||||
## Bundle your security headers
|
||||
|
||||
Manage browser security headers in one spot.
|
||||
|
||||
@@ -17,6 +17,8 @@ In a pre-request handler, `req.matched_route` holds the **pattern string** that
|
||||
|
||||
Because the body has not been read when the pre-request handler runs, you can reject a request — for example on a failed auth check — without consuming a (potentially large) request body. Note that this also means `req.body` and form fields parsed from the body are not available here; inspect headers, the path, query parameters, or `req.matched_route` instead.
|
||||
|
||||
The pre-request handler runs only for requests that match a route. Files served by `set_mount_point()` are answered before route matching, so guard static files in the pre-routing handler.
|
||||
|
||||
## Switch auth per route
|
||||
|
||||
```cpp
|
||||
@@ -37,6 +39,10 @@ svr.set_pre_request_handler(
|
||||
|
||||
`matched_route` is the pattern **before** path parameters are expanded (e.g. `/admin/users/:id`). You compare against the route definition, not the actual request path, so IDs or names don't throw you off.
|
||||
|
||||
The pre-request handler also runs for routes registered with `svr.WebSocket()`. It is called before the `101 Switching Protocols` response, so returning `Handled` sends your HTTP response (such as a 403) and the connection is never upgraded.
|
||||
|
||||
The server accepts a handshake from any `Origin`. A browser sends its cookies even with a handshake that another site starts, so if cookies authenticate the connection, also check `req.get_header_value("Origin")` against your own origins here.
|
||||
|
||||
## Return values
|
||||
|
||||
Same as pre-routing — return `HandlerResponse`.
|
||||
|
||||
@@ -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"});
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 32
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
To customize the response for 4xx or 5xx errors, use `set_error_handler()`. You can replace the plain default error page with your own HTML or JSON.
|
||||
To customize the response for 4xx or 5xx errors, use `set_error_handler()`. By default, an error response has an empty body; an error handler lets you fill it with your own HTML or JSON.
|
||||
|
||||
## Basic usage
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 34
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
To log the requests the server receives and the responses it returns, use `Server::set_logger()`. The callback fires once per completed request, making it the foundation for access logs and metrics collection.
|
||||
To log the requests the server receives and the responses it returns, use `Server::set_logger()`. The callback fires once per request, right before the response is written, making it the foundation for access logs and metrics collection.
|
||||
|
||||
## Basic usage
|
||||
|
||||
@@ -18,6 +18,8 @@ svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
||||
|
||||
The log callback receives both the `Request` and the `Response`. You can grab the method, path, status, client IP, headers, body — whatever you need.
|
||||
|
||||
`req.path` is percent-decoded, so it may contain control characters such as CR/LF. Escape it before writing it to a log file, or a crafted request can forge log lines.
|
||||
|
||||
## Access-log style format
|
||||
|
||||
Here's an Apache/Nginx-ish access log format.
|
||||
@@ -38,6 +40,8 @@ svr.set_logger([](const auto &req, const auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
For a response sent through a content provider, such as a file served from a mount point, `res.body` is empty here, so the size shows `0B`.
|
||||
|
||||
## Measure request time
|
||||
|
||||
To include request duration in the log, stash a start timestamp in `res.user_data` from a pre-routing handler, then subtract in the logger.
|
||||
@@ -48,7 +52,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>(
|
||||
@@ -59,6 +63,8 @@ svr.set_logger([](const auto &req, const auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
Since the logger runs before the response is written, the time doesn't include sending the body.
|
||||
|
||||
For more on `user_data`, see [S12. Pass data between handlers with `res.user_data`](../s12-user-data).
|
||||
|
||||
> **Note:** The logger runs synchronously on the same thread as request processing. Heavy work inside it hurts throughput — push it to a queue and process asynchronously if you need anything expensive.
|
||||
> **Note:** The logger runs synchronously on the same thread as request processing, and all logger calls on a server share one lock. Heavy work inside it hurts throughput — push it to a queue and process asynchronously if you need anything expensive.
|
||||
@@ -43,15 +43,40 @@ svr.listen_after_bind();
|
||||
|
||||
## Check the return values
|
||||
|
||||
`bind_to_port()` returns `false` on failure — typically when the port is already taken. Always check it.
|
||||
`bind_to_port()` returns `false` on failure, for example when you don't have permission to bind to the port. Always check it.
|
||||
|
||||
```cpp
|
||||
if (!svr.bind_to_port("0.0.0.0", 8080)) {
|
||||
std::cerr << "port already in use" << std::endl;
|
||||
std::cerr << "bind failed" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
`listen_after_bind()` blocks until the server stops and returns `true` on a clean shutdown.
|
||||
|
||||
## Detect a port that's already in use
|
||||
|
||||
With the default settings, you can actually bind to a port another server is already using. That's because cpp-httplib sets `SO_REUSEPORT` (Linux, macOS) or `SO_REUSEADDR` (Windows) on the server socket. A restarted server can bind again right away. The flip side is that a second server on the same port starts without an error, and connections get split between the two.
|
||||
|
||||
To make `bind_to_port()` fail on a port in use, replace the socket options with `set_socket_options()`.
|
||||
|
||||
```cpp
|
||||
svr.set_socket_options([](socket_t sock) {
|
||||
#ifdef _WIN32
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1);
|
||||
#else
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
|
||||
#endif
|
||||
});
|
||||
|
||||
if (!svr.bind_to_port("0.0.0.0", 8080)) {
|
||||
std::cerr << "port already in use" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
`set_socket_options()` replaces the defaults entirely. Setting `SO_REUSEADDR` on Linux and macOS keeps the "restarted server can bind again right away" behavior.
|
||||
|
||||
> **Note:** `SO_REUSEADDR` alone isn't enough on Windows. Two sockets that both set it can bind to the same port, so use `SO_EXCLUSIVEADDRUSE` instead.
|
||||
|
||||
> **Note:** To auto-pick a free port, see [S17. Bind to any available port](../s17-bind-any-port). Under the hood, that's just `bind_to_any_port()` + `listen_after_bind()`.
|
||||
@@ -52,6 +52,8 @@ 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.
|
||||
|
||||
> **Note:** `stop()` doesn't interrupt WebSocket handlers. A handler looping on `read()` keeps running as long as its peer stays connected, and `listen()` doesn't return until it ends. Keep track of open WebSocket connections and `close()` them on shutdown, e.g. with `CloseStatus::GoingAway`.
|
||||
@@ -10,7 +10,7 @@ status: "draft"
|
||||
|
||||
| API | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `set_keep_alive_max_count` | 100 | Max requests served over a single connection |
|
||||
| `set_keep_alive_max_count` | 100 | Max requests served over a single connection (0 for no limit) |
|
||||
| `set_keep_alive_timeout` | 5s | How long an idle connection is kept before closing |
|
||||
|
||||
## Basic usage
|
||||
@@ -52,6 +52,6 @@ Set `set_keep_alive_max_count(1)` and every request gets its own connection. Mos
|
||||
|
||||
## Relationship with the thread pool
|
||||
|
||||
A Keep-Alive connection holds a worker thread for its entire lifetime. If `connections × concurrent requests` exceeds the thread pool size, new requests wait. For thread counts, see [S21. Configure the thread pool](../s21-thread-pool).
|
||||
A Keep-Alive connection holds a worker thread for its entire lifetime. The pool adds threads under load, up to its maximum thread count (4× the base count by default). If open connections outnumber that maximum, new connections wait in the queue until one closes. For thread counts, see [S21. Configure the thread pool](../s21-thread-pool).
|
||||
|
||||
> **Note:** For the client side, see [C14. Understand connection reuse and Keep-Alive behavior](../c14-keep-alive). Even when the server closes the connection on timeout, the client reconnects automatically.
|
||||
@@ -66,4 +66,4 @@ You can set the defaults with macros if you want compile-time configuration.
|
||||
#include <httplib.h>
|
||||
```
|
||||
|
||||
> **Note:** A WebSocket connection holds a worker thread for its entire lifetime. For lots of simultaneous WebSocket connections, enable dynamic scaling (e.g. `ThreadPool(8, 64)`).
|
||||
> **Note:** A WebSocket connection holds a worker thread for its entire lifetime. For lots of simultaneous WebSocket connections, raise the maximum thread count (e.g. `ThreadPool(8, 64)`).
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -46,4 +46,4 @@ Certificate verification control, standing up an SSLServer, reading the peer cer
|
||||
- [T03. Start an SSL/TLS server](../t03-ssl-server)
|
||||
- [T05. Access the peer certificate on the server](../t05-peer-cert)
|
||||
|
||||
> **Note:** On macOS with an OpenSSL-family backend, cpp-httplib automatically loads root certificates from the system keychain (via `CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN`, on by default). To disable this, define `CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES`.
|
||||
> **Note:** On macOS, with any of the three backends, cpp-httplib automatically loads root certificates from the system keychain (via `CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN`, on by default). To disable this, define `CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES`.
|
||||
@@ -19,6 +19,8 @@ auto res = cli.Get("/");
|
||||
|
||||
The first argument is the CA certificate file; the second is an optional CA directory. With the OpenSSL backend, you can also pass an `X509_STORE*` directly via `set_ca_cert_store()`.
|
||||
|
||||
Once you set a custom CA, the client trusts only that CA and skips the OS store. To trust both, also call `cli.enable_system_ca(true)`. CA certificates are loaded once, on the client's first connection, so make these settings before the first request.
|
||||
|
||||
## Disable certificate verification (not recommended)
|
||||
|
||||
For development servers or self-signed certificates, you can skip verification entirely.
|
||||
@@ -46,7 +48,7 @@ The certificate itself is still validated, so this is safer than fully disabling
|
||||
|
||||
## Use the OS cert store as-is
|
||||
|
||||
On most Linux distributions, root certificates live in a single file like `/etc/ssl/certs/ca-certificates.crt`. cpp-httplib reads the OS default store at startup, so for most servers you don't need to configure anything.
|
||||
On most Linux distributions, root certificates live in a single file like `/etc/ssl/certs/ca-certificates.crt`. cpp-httplib loads the OS default store on the client's first connection, so for most servers you don't need to configure anything.
|
||||
|
||||
> The same APIs work on the mbedTLS and wolfSSL backends. For choosing between backends, see [T01. Choosing between OpenSSL, mbedTLS, and wolfSSL](../t01-tls-backends).
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ Before a certificate expires, you may want to swap it out without restarting the
|
||||
svr.update_certs_pem(new_cert_pem, new_key_pem);
|
||||
```
|
||||
|
||||
Existing connections keep using the old cert; new connections use the new one.
|
||||
Existing connections keep using the old cert; new connections use the new one. It waits for handshakes in progress to finish, at most the read timeout, and new connections wait until it returns. So don't call it from a TLS callback that runs during a handshake: it would wait for that handshake.
|
||||
|
||||
## Generating a test certificate
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ for (const auto &san : sans) {
|
||||
}
|
||||
```
|
||||
|
||||
There's also a helper to check if a hostname is covered by the SAN list:
|
||||
There's also a helper that checks whether the certificate covers a hostname. It follows the rules of TLS hostname verification: an IP address is matched against the IP address SANs, a name against the DNS SANs, and the CN is used only when there's no DNS SAN.
|
||||
|
||||
```cpp
|
||||
if (cert.check_hostname("alice.corp.example.com")) {
|
||||
@@ -81,7 +81,7 @@ Combined with a pre-request handler, you can keep all authorization logic in one
|
||||
|
||||
## SNI (Server Name Indication)
|
||||
|
||||
cpp-httplib handles SNI automatically. If one server hosts multiple domains, SNI is used under the hood — but normally handlers don't need to care.
|
||||
Clients send SNI automatically. On the server, `req.sni()` returns the name the client asked for. `SSLServer` presents the same certificate whatever that name is, though, so to host several domains on one server, use a certificate that covers all of them. To choose a certificate per name, hook into the TLS backend yourself — with OpenSSL, for example, set a servername callback through the `SSLServer` constructor that takes a context setup callback.
|
||||
|
||||
> **Warning:** `req.peer_cert()` only returns a meaningful value when mTLS is enabled and the client actually presented a certificate. For plain TLS, you get an empty `PeerCert`. Always do the `bool` check before using it.
|
||||
|
||||
|
||||
@@ -21,7 +21,12 @@ int main() {
|
||||
if (result == httplib::ws::ReadResult::Fail) {
|
||||
break;
|
||||
}
|
||||
ws.send(msg); // echo back what we received
|
||||
// echo back what we received, in the same frame type
|
||||
if (result == httplib::ws::ReadResult::Binary) {
|
||||
ws.send(msg.data(), msg.size());
|
||||
} else {
|
||||
ws.send(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -29,13 +34,14 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
Register a WebSocket handler with `svr.WebSocket()`. By the time the handler runs, the WebSocket handshake is already complete. Inside the loop, just `ws.read()` and `ws.send()` to get a working echo.
|
||||
Register a WebSocket handler with `svr.WebSocket()`. By the time the handler runs, the WebSocket handshake is already complete. Inside the loop, just `ws.read()` and `ws.send()` to get a working echo. A binary message goes back through the `data()` + `size()` overload so it stays binary (more on that below).
|
||||
|
||||
The `read()` return value is a `ReadResult` enum:
|
||||
|
||||
- `ReadResult::Text`: received a text message
|
||||
- `ReadResult::Binary`: received a binary message
|
||||
- `ReadResult::Fail`: error, or connection closed
|
||||
- `ReadResult::Timeout`: a read timeout you set with `set_read_timeout()` elapsed with nothing received; the connection is still open. The compile-time default timeout closes the connection and is reported as `Fail` instead — see [W06. Set Timeouts](../w06-websocket-timeouts)
|
||||
|
||||
## Client: talk to the echo server
|
||||
|
||||
@@ -75,7 +81,7 @@ The `std::string` overload sends as **text**; the `const char*` + size overload
|
||||
|
||||
## Thread pool implications
|
||||
|
||||
A WebSocket handler holds its worker thread for the entire life of the connection — one connection per thread. For many concurrent clients, configure a dynamic thread pool.
|
||||
A WebSocket handler holds its worker thread for the entire life of the connection — one connection per thread. The default pool already grows under load, up to 4× its base thread count. For many concurrent clients, raise that maximum.
|
||||
|
||||
```cpp
|
||||
svr.new_task_queue = [] {
|
||||
|
||||
@@ -43,7 +43,7 @@ The default interval is set by the build-time macro `CPPHTTPLIB_WEBSOCKET_PING_I
|
||||
|
||||
## What about Pong?
|
||||
|
||||
The WebSocket protocol requires that Ping frames are answered with Pong frames. cpp-httplib responds to Pings automatically — you don't need to think about it in application code.
|
||||
The WebSocket protocol requires that Ping frames are answered with Pong frames. cpp-httplib answers Pings automatically inside `read()` — as long as your code keeps calling `read()`, you don't need to think about it.
|
||||
|
||||
## Picking an interval
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -75,6 +75,6 @@ The counter is reset whenever `read()` consumes an incoming Pong frame, so this
|
||||
|
||||
`max_missed_pongs` defaults to `0`, which means "never close the connection because of missing pongs." Pings are still sent on the heartbeat interval, but their responses aren't checked. If you want unresponsive-peer detection, set it explicitly to `1` or higher.
|
||||
|
||||
Even with `0`, a dead connection won't linger forever: while your code is inside `read()`, `CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND` (default **300 seconds = 5 minutes**) acts as a backstop and `read()` fails if no frame arrives in time. Think of `max_missed_pongs` as the knob for detecting an unresponsive peer **faster** than that.
|
||||
On the server side, even with `0`, a dead connection won't linger forever: 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 backstop of its own — 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 how you notice one **faster** than that 5-minute fallback.
|
||||
|
||||
> For handling a closed connection, see [W03. Handle connection close](../w03-websocket-close).
|
||||
@@ -67,7 +67,7 @@ To notify in-flight clients that the server is going down, use `GoingAway`.
|
||||
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
||||
```
|
||||
|
||||
The client can inspect that status and decide whether to reconnect.
|
||||
On the client, `read()` just returns `Fail`; the status and reason it received aren't exposed. If the client needs to tell a restart from other closures, send it a message first (say, `ws.send("restarting")`), then call `close()`.
|
||||
|
||||
## Example: a tiny chat with quit
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ switch (result) {
|
||||
case httplib::ws::ReadResult::Fail:
|
||||
// error or closed
|
||||
break;
|
||||
case httplib::ws::ReadResult::Timeout:
|
||||
// read timeout elapsed; the connection is still open
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -82,4 +85,4 @@ if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
|
||||
|
||||
You can mix text and binary in the same connection. A common pattern: JSON for control messages, binary for the actual data — you get efficient handling of metadata and payload both.
|
||||
|
||||
> **Note:** WebSocket frames don't have an infinite size limit. For very large data, chunk it in your application code. cpp-httplib can handle a big frame in one shot, but it does load it all into memory at once.
|
||||
> **Note:** An incoming message can be at most `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default, 0 for no limit). A larger one makes `read()` return `Fail` and ends the connection. Within that limit, a message is held in memory whole, so for very large data, chunk it in your application code.
|
||||
@@ -26,6 +26,8 @@ if (ws.connect()) {
|
||||
|
||||
To disable certificate verification entirely, use `enable_server_certificate_verification(false)`. For details on that behavior, see [T02. Control SSL Certificate Verification](../t02-cert-verification).
|
||||
|
||||
`WebSocketClient` also has `set_server_certificate_verifier()` and `set_session_verifier()` for custom checks, plus the proxy setters (`set_proxy()`, `set_proxy_basic_auth()`, `set_proxy_bearer_token_auth()`, `set_proxy_digest_auth()`, `set_no_proxy()`). CA certificates are loaded on the first `connect()`, so set them before that.
|
||||
|
||||
## Presenting a client certificate (mTLS)
|
||||
|
||||
`ws::WebSocketClient` has a constructor overload that takes a `PemMemory` struct, letting `wss://` connections present a client certificate.
|
||||
|
||||
@@ -9,7 +9,7 @@ status: "draft"
|
||||
| Kind | API | Default |
|
||||
| --- | --- | --- |
|
||||
| Connection | `set_connection_timeout` | 300s |
|
||||
| Read | `set_read_timeout` | 300s (`CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND`) |
|
||||
| Read | `set_read_timeout` | none — waits forever (`CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND`) |
|
||||
| Write | `set_write_timeout` | 5s |
|
||||
|
||||
## Basic usage
|
||||
@@ -26,7 +26,7 @@ if (ws.connect()) {
|
||||
}
|
||||
```
|
||||
|
||||
Set these before calling `connect()`.
|
||||
Set the connection and write timeouts before calling `connect()`. The read timeout can be changed at any time — setting it on an open connection takes effect on the next `read()`.
|
||||
|
||||
## Use `std::chrono`
|
||||
|
||||
@@ -40,9 +40,44 @@ ws.set_read_timeout(30s);
|
||||
ws.set_write_timeout(10s);
|
||||
```
|
||||
|
||||
## Watch out for what the read timeout means
|
||||
## What the read timeout means
|
||||
|
||||
`set_read_timeout()` applies to a single `read()` call. If no message arrives within that time, `read()` returns `ReadResult::Fail`. For connections where long idle periods are normal — waiting on notifications, for example — set a longer timeout, or reconnect from your application code when the read fails.
|
||||
`set_read_timeout()` applies to a single `read()` call. If no message arrives within that time, `read()` returns `ReadResult::Timeout`: **the connection is still open** and nothing was consumed, so you can send on it and read again. That is what separates it from `ReadResult::Fail`, which means the connection is gone.
|
||||
|
||||
This is what lets one thread own a connection in both directions:
|
||||
|
||||
```cpp
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
ws.set_read_timeout(100ms);
|
||||
std::string msg;
|
||||
while (ws.is_open()) {
|
||||
auto r = ws.read(msg);
|
||||
if (r == httplib::ws::Timeout) {
|
||||
flush_outgoing(ws); // nothing arrived — send whatever is queued
|
||||
continue;
|
||||
}
|
||||
if (r == httplib::ws::Fail) { break; }
|
||||
handle(msg);
|
||||
}
|
||||
```
|
||||
|
||||
Without a read timeout, `read()` blocks until a message arrives, so the thread holding the connection never gets to its writes.
|
||||
|
||||
Two things to know about `Timeout`:
|
||||
|
||||
- It leaves `msg` untouched, and it is non-zero. So `while (ws.read(msg))` is not usable once a read timeout is set — the loop would keep running with the *previous* message still in `msg`.
|
||||
- It is only reported on a message boundary. If the timeout elapses partway through a fragmented message, that message cannot be resumed and `read()` returns `Fail`.
|
||||
|
||||
For connections where long idle periods are normal — waiting on notifications, for example — either leave the read timeout unset, or treat `Timeout` as the no-op it is and keep looping.
|
||||
|
||||
## On the server side
|
||||
|
||||
A handler's `ws::WebSocket` has `set_read_timeout()` too, and the pattern above is how a handler relays between connections instead of parking in `read()`.
|
||||
|
||||
The server default is 300s (`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`) rather than "forever": it is a backstop that reclaims a worker from a peer that has gone silent, since a WebSocket handler holds its worker for the life of the connection.
|
||||
|
||||
Because it is a backstop rather than something the handler asked for, it does not surface as `Timeout`. When it elapses, `read()` returns `Fail` and closes the connection, so a handler written as `while (ws.read(msg))` ends the way it always has. Only a timeout the handler set itself with `set_read_timeout()` comes back as `Timeout`.
|
||||
|
||||
> Unresponsive-peer detection via Ping/Pong is a separate mechanism. See [W02. Set a WebSocket Heartbeat](../w02-websocket-ping) for details.
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ When you need a quick HTTP server or client in C++, you want something that just
|
||||
|
||||
The API uses a lambda-based design that feels natural. It runs anywhere you have a C++11 or later compiler. Windows, macOS, Linux — use whatever environment you already have.
|
||||
|
||||
HTTPS works too. Just link OpenSSL or mbedTLS, and both server and client gain TLS support. Content-Encoding (gzip, Brotli, etc.), file uploads, and other features you actually need in real-world development are all included. WebSocket is also supported.
|
||||
HTTPS works too. Just link OpenSSL, Mbed TLS, or wolfSSL, and both server and client gain TLS support. Content-Encoding (gzip, Brotli, etc.), file uploads, and other features you actually need in real-world development are all included. WebSocket is also supported.
|
||||
|
||||
Under the hood, it uses blocking I/O with a thread pool. It's not built for handling massive numbers of simultaneous connections. But for API servers, embedded HTTP in tools, mock servers for testing, and many other use cases, it delivers solid performance.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -76,7 +76,7 @@ Defining `CPPHTTPLIB_OPENSSL_SUPPORT` enables `httplib::Client("https://...")` t
|
||||
|
||||
## 4.2 Defining the Model List
|
||||
|
||||
Let's define the list of models that the app can handle. Here are four models we've verified for translation tasks.
|
||||
Let's define the list of models that the app can handle. Here are three models we've verified for translation tasks.
|
||||
|
||||
```cpp
|
||||
struct ModelInfo {
|
||||
@@ -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;
|
||||
|
||||
@@ -875,6 +875,7 @@ The only server-side change is the single `set_mount_point` line. Add it before
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
@@ -934,12 +935,11 @@ std::filesystem::path get_models_dir() {
|
||||
// Model download
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
// Abort the download if progress_cb returns false
|
||||
// If progress_cb returns false, the download is aborted
|
||||
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
|
||||
cli.set_follow_location(true); // Hugging Face redirects to a CDN
|
||||
|
||||
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
|
||||
auto path = get_models_dir() / model.filename;
|
||||
@@ -949,12 +949,12 @@ bool download_model(const ModelInfo &model,
|
||||
if (!ofs) { return false; }
|
||||
|
||||
auto res = cli.Get(url,
|
||||
// content_receiver: receive chunks and write to file
|
||||
// content_receiver: receive data chunk by chunk and write to file
|
||||
[&](const char *data, size_t len) {
|
||||
ofs.write(data, len);
|
||||
return ofs.good();
|
||||
},
|
||||
// progress: report download progress (return false to abort)
|
||||
// progress: report download progress (returning false aborts)
|
||||
[&, last_pct = -1](size_t current, size_t total) mutable {
|
||||
int pct = total ? (int)(current * 100 / total) : 0;
|
||||
if (pct == last_pct) return true; // Skip if same value
|
||||
@@ -988,11 +988,11 @@ void signal_handler(int sig) {
|
||||
}
|
||||
|
||||
int main() {
|
||||
// Create model storage directory
|
||||
// Create the model storage directory
|
||||
auto models_dir = get_models_dir();
|
||||
std::filesystem::create_directories(models_dir);
|
||||
|
||||
// Auto-download default model if not present
|
||||
// Automatically download the default model if not yet present
|
||||
std::string selected_model = MODELS[0].filename;
|
||||
auto path = models_dir / selected_model;
|
||||
if (!std::filesystem::exists(path)) {
|
||||
@@ -1007,10 +1007,7 @@ int main() {
|
||||
std::cout << std::endl;
|
||||
}
|
||||
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);
|
||||
std::mutex llm_mutex; // Protect access during model switching
|
||||
|
||||
svr.set_logger([](const auto &req, const auto &res) {
|
||||
std::cout << req.method << " " << req.path << " -> " << res.status
|
||||
@@ -1025,6 +1022,7 @@ int main() {
|
||||
|
||||
svr.Post("/translate",
|
||||
[&](const httplib::Request &req, httplib::Response &res) {
|
||||
// JSON parsing and validation (see Chapter 2 for details)
|
||||
auto input = json::parse(req.body, nullptr, false);
|
||||
if (input.is_discarded()) {
|
||||
res.status = 400;
|
||||
@@ -1048,6 +1046,7 @@ int main() {
|
||||
". Output only the translation, nothing else.\n\n" + text;
|
||||
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(llm_mutex);
|
||||
auto translation = llm.chat(prompt);
|
||||
res.set_content(json{{"translation", translation}}.dump(),
|
||||
"application/json");
|
||||
@@ -1057,7 +1056,7 @@ int main() {
|
||||
}
|
||||
});
|
||||
|
||||
// --- SSE streaming translation (Chapter 3) --------------------------------
|
||||
// --- SSE streaming translation (Chapter 3) -------------------------------
|
||||
|
||||
svr.Post("/translate/stream",
|
||||
[&](const httplib::Request &req, httplib::Response &res) {
|
||||
@@ -1086,6 +1085,7 @@ int main() {
|
||||
res.set_chunked_content_provider(
|
||||
"text/event-stream",
|
||||
[&, prompt](size_t, httplib::DataSink &sink) {
|
||||
std::lock_guard<std::mutex> lock(llm_mutex);
|
||||
try {
|
||||
llm.chat(prompt, [&](std::string_view token) {
|
||||
sink.os << "data: "
|
||||
@@ -1103,7 +1103,7 @@ int main() {
|
||||
});
|
||||
});
|
||||
|
||||
// --- Model list (Chapter 4) -----------------------------------------------
|
||||
// --- Model list (Chapter 4) ----------------------------------------------
|
||||
|
||||
svr.Get("/models",
|
||||
[&](const httplib::Request &, httplib::Response &res) {
|
||||
@@ -1122,7 +1122,7 @@ int main() {
|
||||
res.set_content(json{{"models", arr}}.dump(), "application/json");
|
||||
});
|
||||
|
||||
// --- Model selection (Chapter 4) ------------------------------------------
|
||||
// --- Model selection (Chapter 4) -----------------------------------------
|
||||
|
||||
svr.Post("/models/select",
|
||||
[&](const httplib::Request &req, httplib::Response &res) {
|
||||
@@ -1148,16 +1148,16 @@ int main() {
|
||||
|
||||
const auto &model = *it;
|
||||
|
||||
// Always respond with SSE (same format whether downloaded or not)
|
||||
// Always respond with SSE (same format whether already downloaded or not)
|
||||
res.set_chunked_content_provider(
|
||||
"text/event-stream",
|
||||
[&, model](size_t, httplib::DataSink &sink) {
|
||||
// SSE event send helper
|
||||
// SSE event sending helper
|
||||
auto send = [&](const json &event) {
|
||||
sink.os << "data: " << event.dump() << "\n\n";
|
||||
};
|
||||
|
||||
// Download if not yet downloaded (report progress via SSE)
|
||||
// Download if not yet present (report progress via SSE)
|
||||
auto path = get_models_dir() / model.filename;
|
||||
if (!std::filesystem::exists(path)) {
|
||||
bool ok = download_model(model, [&](int pct) {
|
||||
@@ -1173,8 +1173,11 @@ int main() {
|
||||
|
||||
// Load and switch to the model
|
||||
send({{"status", "loading"}});
|
||||
llm = llamalib::Llama{path};
|
||||
selected_model = model.filename;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(llm_mutex);
|
||||
llm = llamalib::Llama{path};
|
||||
selected_model = model.filename;
|
||||
}
|
||||
|
||||
send({{"status", "ready"}});
|
||||
sink.done();
|
||||
@@ -1182,11 +1185,11 @@ int main() {
|
||||
});
|
||||
});
|
||||
|
||||
// --- Static file serving (Chapter 5) --------------------------------------
|
||||
// --- Static file serving (Chapter 5) -------------------------------------
|
||||
|
||||
svr.set_mount_point("/", "./public");
|
||||
|
||||
// Allow graceful shutdown via `Ctrl+C` (`SIGINT`) or `kill` (`SIGTERM`)
|
||||
// Allow the server to be stopped with `Ctrl+C` (`SIGINT`) or `kill` (`SIGTERM`)
|
||||
signal(SIGINT, signal_handler);
|
||||
signal(SIGTERM, signal_handler);
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -680,9 +675,10 @@ int main() {
|
||||
To summarize the changes from Chapter 5:
|
||||
|
||||
- `#include <csignal>` replaced with `#include <thread>`, `<cpp-embedlib-httplib.h>`, `"WebAssets.h"`, `"webview/webview.h"`
|
||||
- Removed the `signal_handler` function
|
||||
- Removed the `signal_handler` function and moved `svr` into `main()`
|
||||
- `svr.set_mount_point("/", "./public")` replaced with `httplib::mount(svr, Web::FS)`
|
||||
- `svr.listen("127.0.0.1", 8080)` replaced with `bind_to_any_port` + `listen_after_bind` + WebView event loop
|
||||
- Added `setup_macos_edit_menu()` and its `<objc/objc-runtime.h>` include (macOS only)
|
||||
|
||||
Not a single line of handler code has changed. The REST API, SSE streaming, and model management built through Chapter 5 all work as-is.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -55,7 +59,7 @@ Compatibility with existing tools and libraries is a big design decision. We des
|
||||
|
||||
## 7.3 Concurrent Request Handling
|
||||
|
||||
Our server processes requests one at a time. If another request arrives while a translation is in progress, it waits until the previous inference finishes. This is fine for a desktop app used by one person, but it becomes a problem for a server shared by multiple users.
|
||||
Our server runs inference one request at a time. If another request arrives while a translation is in progress, it waits until the previous inference finishes. This is fine for a desktop app used by one person, but it becomes a problem for a server shared by multiple users.
|
||||
|
||||
`llama-server` handles concurrent requests through a mechanism called **slots**.
|
||||
|
||||
@@ -63,7 +67,7 @@ Our server processes requests one at a time. If another request arrives while a
|
||||
|
||||
The key point is that tokens from each slot are not inferred **one by one in sequence**, but rather **all at once in a single batch**. GPUs excel at parallel processing, so processing two users simultaneously takes almost the same time as processing one. This is called "continuous batching."
|
||||
|
||||
In our server, cpp-httplib's thread pool assigns one thread per request, but the inference itself runs single-threaded inside `llm.chat()`. `llama-server` consolidates this inference step into a shared batch processing loop.
|
||||
In our server, cpp-httplib's thread pool serves each connection on its own worker thread, so requests on different connections are handled concurrently. Inference, however, is serialized by `llm_mutex`, so only one `llm.chat()` runs at a time. `llama-server` consolidates this inference step into a shared batch processing loop.
|
||||
|
||||
## 7.4 Differences in SSE Format
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -107,6 +107,8 @@ svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws)
|
||||
});
|
||||
```
|
||||
|
||||
A check inside the handler runs after the handshake has completed. To refuse the connection with an HTTP status such as 401 before it is upgraded, use `set_pre_request_handler()` instead. It also runs for WebSocket routes. See [S11. Authenticate per route with a pre-request handler](../../cookbook/s11-pre-request).
|
||||
|
||||
## Using WSS
|
||||
|
||||
WebSocket over HTTPS (WSS) is also supported. On the server side, just register a WebSocket handler on `httplib::SSLServer`.
|
||||
|
||||
@@ -21,7 +21,9 @@ if (result) {
|
||||
}
|
||||
```
|
||||
|
||||
You can also pass a `content_receiver` callback to `Get()`. This approach works with Keep-Alive.
|
||||
Note that `stream::Get()` reads no more of the body than the client's `set_payload_max_length()` allows, which is 100MB by default. For larger downloads, raise it, or set it to 0 for no limit.
|
||||
|
||||
You can also pass a `content_receiver` callback to `Get()`. This approach works with Keep-Alive, and it has no size limit unless you set one with `set_payload_max_length()`.
|
||||
|
||||
```cpp
|
||||
httplib::Client cli("http://localhost:8080");
|
||||
@@ -50,7 +52,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 +157,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 +170,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 +207,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レスポンスを受け取る
|
||||
|
||||
|
||||
@@ -50,6 +50,6 @@ httplib::Headers headers = {
|
||||
auto res = cli.Get("/users", headers);
|
||||
```
|
||||
|
||||
リクエスト単位で渡したヘッダーはデフォルトヘッダーに**追加**されます。両方がサーバーに送られます。
|
||||
リクエスト単位で渡したヘッダーはデフォルトヘッダーに**追加**され、両方がサーバーに送られます。デフォルトヘッダーと同じ名前のヘッダーを渡した場合は、リクエスト単位のものだけが送られます。
|
||||
|
||||
> Bearerトークンを使った認証の詳細は[C06. BearerトークンでAPIを呼ぶ](../c06-bearer-token)を参照してください。
|
||||
@@ -33,6 +33,8 @@ auto res = cli.Get("/");
|
||||
|
||||
多くのサイトはHTTPアクセスをHTTPSへリダイレクトします。`set_follow_location(true)`を有効にしておけば、こうしたケースも透過的に扱えます。スキームやホストが変わっても自動で追従します。
|
||||
|
||||
リダイレクト先が別のオリジン(スキーム、ホスト、ポートのどれかが違う)の場合、`Authorization`、`Cookie`、`Proxy-Authorization`ヘッダーは外され、`set_basic_auth()`などで設定した認証情報も送られません。クライアント証明書も提示しません。それ以外のヘッダーはデフォルトヘッダーも含めてそのまま送られ、タイムアウト、ペイロードの上限、TLSの検証設定も引き継がれます。
|
||||
|
||||
> **Warning:** HTTPSへのリダイレクトを追従するには、cpp-httplibをOpenSSL(または他のTLSバックエンド)付きでビルドしておく必要があります。TLSサポートがないと、HTTPSへのリダイレクトは失敗します。
|
||||
|
||||
> **Note:** リダイレクトを追従すると、リクエストの実行時間は伸びます。タイムアウトの設定は[C12. タイムアウトを設定する](../c12-timeouts)を参照してください。
|
||||
@@ -12,7 +12,7 @@ status: "draft"
|
||||
httplib::Client cli("https://storage.example.com");
|
||||
|
||||
auto [size, provider] = httplib::make_file_body("backup.tar.gz");
|
||||
if (size == 0) {
|
||||
if (!provider) {
|
||||
std::cerr << "Failed to open file" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ auto res = cli.Put("/bucket/backup.tar.gz", size,
|
||||
|
||||
## ファイルが開けなかったとき
|
||||
|
||||
`make_file_body()`は開けなかった場合、`size`を`0`、`provider`を空の関数オブジェクトとして返します。そのまま送信するとおかしな結果になるので、必ず`size`をチェックしてください。
|
||||
`make_file_body()`は開けなかった場合、`size`を`0`、`provider`を空の関数オブジェクトとして返します。そのまま送信すると空のボディが送られてしまうので、必ず`provider`をチェックしてください。`size`では判定できません。空のファイルでも`size`は`0`になり、そのときの`provider`は正しく使えるからです。
|
||||
|
||||
> **Warning:** `make_file_body()`はContent-Lengthを最初に確定させる必要があるため、ファイルサイズをあらかじめ取得します。送信中にファイルサイズが変わる可能性がある場合は、このAPIには向きません。
|
||||
|
||||
|
||||
@@ -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)も参照してください。
|
||||
@@ -12,6 +12,8 @@ status: "draft"
|
||||
| 読み取りタイムアウト | `set_read_timeout` | 300秒 | レスポンスを受信する際の1回の`recv`待ち時間 |
|
||||
| 書き込みタイムアウト | `set_write_timeout` | 5秒 | リクエストを送信する際の1回の`send`待ち時間 |
|
||||
|
||||
HTTPSでは、接続タイムアウトがTLSハンドシェイク全体の制限時間にもなります。時間内にハンドシェイクが終わらないと、`Error::SSLConnection`で失敗します。
|
||||
|
||||
## 基本の使い方
|
||||
|
||||
```cpp
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 13
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
[C12. タイムアウトを設定する](../c12-timeouts)で紹介した3種類のタイムアウトは、いずれも「1回の`send`や`recv`」に対するものです。リクエスト全体の所要時間に上限を設けたい場合は、`set_max_timeout()`を使います。
|
||||
[C12. タイムアウトを設定する](../c12-timeouts)で紹介した3種類のタイムアウトは、どれも一部の待ち時間にしか効きません。読み取りと書き込みのタイムアウトは「1回の`recv`や`send`」に、接続タイムアウトは接続の確立に対するものです。リクエスト全体の所要時間に上限を設けたい場合は、`set_max_timeout()`を使います。
|
||||
|
||||
## 基本の使い方
|
||||
|
||||
@@ -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、PATCHのリクエストボディが圧縮されて送信されます。圧縮方式は、ビルドで有効にしたもののうち、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`で失敗します。うまく動かないときは、まずマクロの定義を確認しましょう。
|
||||
@@ -17,6 +17,8 @@ auto res = cli.Get("/users");
|
||||
|
||||
プロキシ経由でリクエストが送られます。HTTPSの場合はCONNECTメソッドでトンネルが張られるので、cpp-httplib側で特別な設定は要りません。
|
||||
|
||||
プロキシがトンネルを拒否すると、リクエストは`Error::ProxyConnection`で失敗します。ただし407だけは例外で、レスポンスとして返ってきます。`res`はtruthyで`res->status`は407ですが、`res.error()`は`Error::ProxyConnection`のままです。
|
||||
|
||||
## プロキシに認証を設定する
|
||||
|
||||
プロキシ自体が認証を要求する場合は、`set_proxy_basic_auth()`や`set_proxy_bearer_token_auth()`を使います。
|
||||
@@ -55,7 +57,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"});
|
||||
```
|
||||
|
||||
エントリは次のいずれかです。
|
||||
@@ -69,6 +71,20 @@ cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
|
||||
|
||||
不正な書式のエントリは黙って捨てられます。`example.com:8080`のようなポート指定エントリはサポート外です(cpp-httplibの他のホストキーAPIもホスト名のみを扱う設計のため)。
|
||||
|
||||
## WebSocketでもプロキシを使う
|
||||
|
||||
`ws::WebSocketClient`にも同じプロキシ設定があります。
|
||||
|
||||
```cpp
|
||||
httplib::ws::WebSocketClient cli("wss://ws.example.com/chat");
|
||||
cli.set_proxy("proxy.internal", 8080);
|
||||
cli.set_proxy_basic_auth("user", "password");
|
||||
|
||||
auto res = cli.connect();
|
||||
```
|
||||
|
||||
`ws://`でも`wss://`でも、CONNECTメソッドでトンネルを張ってからWebSocketのハンドシェイクを行います。`set_no_proxy()`も同じように使えます。
|
||||
|
||||
## 環境変数からプロキシ設定を読み込む
|
||||
|
||||
cpp-httplib本体は`HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`を読みません。`set_ca_cert_path()`と同じで、設定APIは常に明示的にしています。環境変数を反映させたい場合は、アプリ側で読んで`set_proxy()`や`set_no_proxy()`に渡してください。
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 17
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
`cli.Get()`や`cli.Post()`は`Result`型を返します。リクエストが失敗したとき(サーバーに到達できなかった、タイムアウトしたなど)、返り値は「falsy」になります。詳しい原因を知りたい場合は`Result::error()`を使います。
|
||||
`cli.Get()`や`cli.Post()`は`Result`型を返します。リクエストが失敗したとき(サーバーに到達できなかった、タイムアウトしたなど)、返り値は「falsy」になります(例外が1つあり、下の表で説明します)。詳しい原因を知りたい場合は`Result::error()`を使います。
|
||||
|
||||
## 基本の判定
|
||||
|
||||
@@ -27,18 +27,20 @@ if (res) {
|
||||
|
||||
| 値 | 意味 |
|
||||
| --- | --- |
|
||||
| `Error::Connection` | サーバーに接続できなかった |
|
||||
| `Error::Connection` | サーバーに接続できなかった。または、使えないURL(authorityにuserinfoやバックスラッシュがある、ポートが不正など)から`Client`を作った。後者の場合は`cli.is_valid()`が`false`になる |
|
||||
| `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::ExceedMaxPayloadSize` | レスポンスボディが`set_payload_max_length()`の上限を超えた(解凍後に超えた場合も含む) |
|
||||
| `Error::Timeout` | `stream::Get()`や`SSEClient`で、ボディの読み取りがタイムアウトした |
|
||||
| `Error::ExceedRedirectCount` | リダイレクト回数が上限を超えた |
|
||||
| `Error::SSLConnection` | TLSハンドシェイクに失敗 |
|
||||
| `Error::SSLServerVerification` | サーバー証明書の検証に失敗 |
|
||||
| `Error::Canceled` | 進捗コールバックから`false`が返された |
|
||||
| `Error::ProxyConnection` | プロキシがCONNECTのトンネルを拒否した。ただし407は例外で、`res`はtruthyかつ`res->status == 407`になり、`res.error()`は`Error::ProxyConnection`のまま |
|
||||
| `Error::Canceled` | 進捗コールバック、`ContentReceiver`、`ResponseHandler`、アップロード用のコンテンツプロバイダのいずれかから`false`が返された |
|
||||
|
||||
## ステータスコードとの使い分け
|
||||
|
||||
`res`が truthy でも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
|
||||
`res`がtruthyでも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
|
||||
|
||||
```cpp
|
||||
auto res = cli.Get("/api/data");
|
||||
|
||||
@@ -17,26 +17,34 @@ if (!res) {
|
||||
std::cerr << "error: " << httplib::to_string(err) << std::endl;
|
||||
|
||||
if (err == httplib::Error::SSLConnection ||
|
||||
err == httplib::Error::SSLServerVerification) {
|
||||
err == httplib::Error::SSLServerVerification ||
|
||||
err == httplib::Error::Read || err == httplib::Error::Write) {
|
||||
std::cerr << "ssl_error: " << res.ssl_error() << std::endl;
|
||||
std::cerr << "ssl_backend_error: " << res.ssl_backend_error() << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`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_*`)が入ります。
|
||||
|
||||
ハンドシェイクのあとで失敗したリクエストは、`Error::Read`や`Error::Write`を返します。その場合も、`ssl_error()`と`ssl_backend_error()`には原因となったTLSのエラーが入ります。たとえば、サーバーが要求するクライアント証明書を送らなかった場合、OpenSSLのエラーは「tlsv13 alert certificate required」になります。どちらの値もリクエストごとにリセットされ、TLSのエラーが絡んでいなければ`0`です。
|
||||
|
||||
## 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;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ cli.set_error_logger([](const httplib::Error &err, const httplib::Request *req)
|
||||
});
|
||||
```
|
||||
|
||||
第2引数の`req`はヌルポインタのこともあります。リクエストを組み立てる前の段階で失敗した場合です。使う前に必ずヌルチェックしてください。
|
||||
失敗したリクエストは、送ったリクエストと一緒に1回だけ報告されます。リダイレクト先で失敗した場合も同じです。`open_stream()`や`stream::Get()`でストリームを開くのに失敗した場合も同じように報告され、ボディを読む途中のエラーは`read_error()`で返ります。`req`がヌルポインタになるのは、どのリクエストにも属さないエラーをサーバーのエラーロガーが受け取るときだけです。
|
||||
|
||||
## 両方を組み合わせる
|
||||
|
||||
|
||||
@@ -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,9 @@ sse.on_error([](httplib::Error err) {
|
||||
});
|
||||
```
|
||||
|
||||
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。
|
||||
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。ただし、サーバーが204、403、404のいずれかを返したときや、`set_max_reconnect_attempts()`で決めた回数を使い切ったときは再接続しません。
|
||||
|
||||
また、1つのイベントや、まだ改行が来ていない行が`CPPHTTPLIB_SSE_MAX_EVENT_LENGTH`(デフォルトは16MB、0なら無制限)を超えたときも止まります。このときエラーハンドラには`Error::ExceedMaxPayloadSize`が渡されます。イベントストリームには終わりがないので、クライアントの`set_payload_max_length()`はストリーム全体には適用されません。
|
||||
|
||||
## 非同期で動かす
|
||||
|
||||
@@ -88,6 +90,8 @@ sse.set_max_reconnect_attempts(10); // 10回まで(0=無制限)
|
||||
|
||||
`SSEClient`は受信したイベントの`id`を内部で保持していて、再接続時に`Last-Event-ID`ヘッダーとして送ってくれます。この挙動はサーバー側で`id:`付きイベントを送っていれば自動で有効になります。
|
||||
|
||||
空の`id:`を受け取ると、保持しているIDはクリアされます。ヘッダーの値として送れない`id:`(NULなどの制御文字を含むものや、前後に空白があるもの)は無視され、それまでのIDがそのまま残ります。
|
||||
|
||||
```cpp
|
||||
std::cout << "last id: " << sse.last_event_id() << std::endl;
|
||||
```
|
||||
|
||||
@@ -44,6 +44,8 @@ svr.Get(R"(/users/(\d+))", [](const httplib::Request &req, httplib::Response &re
|
||||
|
||||
パターンに括弧を使うと、マッチした部分が`req.matches`に入ります。`req.matches[0]`はパス全体、`req.matches[1]`以降がキャプチャです。
|
||||
|
||||
正規表現のルートは、`CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH`(デフォルトは256)より長いパスには適用されず、マッチしなかったものとして扱われます。長い入力で`std::regex`がスタックを使い果たさないための制限です。もっと長いパスを扱いたい場合は、このマクロに大きな値を定義してください。
|
||||
|
||||
## どちらを使うか
|
||||
|
||||
- 単純なIDやスラッグなら`:name`でじゅうぶん。読みやすく、型が自明です
|
||||
|
||||
@@ -10,11 +10,18 @@ HTML、CSS、画像などの静的ファイルを配信したいときは、`set
|
||||
|
||||
```cpp
|
||||
httplib::Server svr;
|
||||
svr.set_mount_point("/", "./public");
|
||||
if (!svr.set_mount_point("/", "./public")) {
|
||||
// ./publicが存在しない
|
||||
return 1;
|
||||
}
|
||||
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に反映されます。
|
||||
`set_mount_point()`はディレクトリが存在しないと`false`を返すので、戻り値を確認しておきましょう。
|
||||
|
||||
`./public/index.html`には`http://localhost:8080/index.html`で、`./public/css/style.css`には`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。
|
||||
|
||||
ディレクトリへのリクエストには、その中の`index.html`を返します。末尾のスラッシュがないリクエスト(`/docs`)は、`/docs/`へリダイレクト(301)されます。マウントしたディレクトリの外を指すシンボリックリンクには403を返します。
|
||||
|
||||
## 複数のマウントポイント
|
||||
|
||||
@@ -26,11 +33,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 +51,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()`で送ります。こうすれば、メモリに載るのは常に小さなチャンクだけです。
|
||||
|
||||
## ファイルをそのまま返す
|
||||
|
||||
|
||||
@@ -48,22 +48,30 @@ svr.Post("/upload",
|
||||
const httplib::ContentReader &content_reader) {
|
||||
std::ofstream ofs;
|
||||
|
||||
content_reader(
|
||||
auto ok = content_reader(
|
||||
[&](const httplib::FormData &file) {
|
||||
if (!file.filename.empty()) {
|
||||
ofs.open("uploads/" + file.filename, std::ios::binary);
|
||||
}
|
||||
return static_cast<bool>(ofs);
|
||||
if (ofs.is_open()) { ofs.close(); } // 前のファイルを閉じる
|
||||
if (file.filename.empty()) { return true; } // 普通のフィールドは読み飛ばす
|
||||
|
||||
auto name = httplib::sanitize_filename(file.filename);
|
||||
if (name.empty()) { return false; } // 安全でない名前は拒否
|
||||
|
||||
ofs.open("uploads/" + name, std::ios::binary);
|
||||
return ofs.is_open();
|
||||
},
|
||||
[&](const char *data, size_t len) {
|
||||
if (!ofs.is_open()) { return true; } // ファイルのパートではない
|
||||
ofs.write(data, len);
|
||||
return static_cast<bool>(ofs);
|
||||
});
|
||||
|
||||
if (!ok) { return; } // ステータスは設定済み
|
||||
res.set_content("uploaded", "text/plain");
|
||||
});
|
||||
```
|
||||
|
||||
ヘッダーのコールバックはパートごとに呼ばれるので、次のファイルを開く前に前のファイルを閉じています。`file.filename`はクライアントが送ってきた値そのままなので、必ず`httplib::sanitize_filename()`を通してください。空文字列が返ったら、安全でない名前です。
|
||||
|
||||
メモリには常に小さなチャンクしか載らないので、ギガバイト級のファイルでも扱えます。
|
||||
|
||||
## パート数は自分で数える
|
||||
@@ -96,7 +104,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()`を使ってください。
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ svr.set_pre_routing_handler(
|
||||
});
|
||||
```
|
||||
|
||||
Pre-routingハンドラは、**ルーティングよりも前**に呼ばれます。どのハンドラにもマッチしないリクエストも含めて、すべてのリクエストを捕まえられます。
|
||||
Pre-routingハンドラは、**ルーティングよりも前**に呼ばれます。どのハンドラにもマッチしないリクエストも含めて、すべてのリクエストを捕まえられます。ただし、リクエストラインやヘッダーの解析中に拒否されたリクエスト(不正なリクエストの400、長すぎるURIの414、不正な`Range`の416)には、このハンドラが呼ばれる前にサーバーが応答します。
|
||||
|
||||
戻り値の`HandlerResponse`がポイントです。
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ svr.Options("/.*", [](const auto &req, auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
`/.*`は正規表現のルートなので、`CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH`(デフォルトは256)より長いパスには適用されません。パスがそれより長くなりうるなら、pre-routingハンドラで`OPTIONS`を処理してください。
|
||||
|
||||
## セキュリティヘッダーをまとめて付ける
|
||||
|
||||
ブラウザ向けのセキュリティヘッダーを一箇所で管理できます。
|
||||
|
||||
@@ -17,6 +17,8 @@ Pre-requestハンドラなら、`req.matched_route`に「マッチしたパタ
|
||||
|
||||
Pre-requestハンドラが呼ばれる時点ではボディがまだ読まれていないので、認証に失敗したリクエストなどを、(巨大かもしれない)ボディを読み込む前に拒否できます。その代わり、`req.body`やボディから解析されるフォームフィールドはこの時点では参照できません。ヘッダ・パス・クエリパラメータ・`req.matched_route`を使って判断してください。
|
||||
|
||||
Pre-requestハンドラが呼ばれるのは、ルートにマッチしたリクエストだけです。`set_mount_point()`で配信するファイルはルートのマッチングより前に返されるので、静的ファイルを守りたいときはPre-routingハンドラでチェックしてください。
|
||||
|
||||
## ルートごとに認証を切り替える
|
||||
|
||||
```cpp
|
||||
@@ -37,6 +39,10 @@ svr.set_pre_request_handler(
|
||||
|
||||
`matched_route`はパスパラメーターを展開する**前**のパターン文字列(例: `/admin/users/:id`)です。特定の値ではなく、ルート定義のパターンで判定できるので、IDや名前に左右されません。
|
||||
|
||||
`svr.WebSocket()`で登録したルートでも、Pre-requestハンドラは呼ばれます。呼ばれるのは`101 Switching Protocols`を返す前なので、`Handled`を返すとそのHTTPレスポンス(403など)がそのまま返り、WebSocketへのアップグレードは行われません。
|
||||
|
||||
サーバーはどの`Origin`からのハンドシェイクも受け付けます。ブラウザは別のサイトが始めたハンドシェイクにもCookieを付けて送るので、Cookieで接続を認証している場合は、`req.get_header_value("Origin")`が自分のオリジンかどうかもここで確認してください。
|
||||
|
||||
## 戻り値の意味
|
||||
|
||||
Pre-routingハンドラと同じく、`HandlerResponse`を返します。
|
||||
|
||||
@@ -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`で取ろうとすると失敗します。
|
||||
@@ -4,7 +4,7 @@ order: 32
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
404や500のような**ハンドラが返したエラーレスポンス**を加工したいときは、`set_error_handler()`を使います。デフォルトの味気ないエラーページを、独自のHTMLやJSONに差し替えられます。
|
||||
404や500のような**ハンドラが返したエラーレスポンス**を加工したいときは、`set_error_handler()`を使います。エラーレスポンスのボディはデフォルトでは空ですが、エラーハンドラで独自のHTMLやJSONを入れられます。
|
||||
|
||||
## 基本の使い方
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ order: 34
|
||||
status: "draft"
|
||||
---
|
||||
|
||||
サーバーが受け取ったリクエストと返したレスポンスをログに残したいときは、`Server::set_logger()`を使います。各リクエストの処理が完了するたびに呼ばれるので、アクセスログやメトリクス収集の土台になります。
|
||||
サーバーが受け取ったリクエストと返したレスポンスをログに残したいときは、`Server::set_logger()`を使います。リクエストごとに、レスポンスを書き出す直前に呼ばれるので、アクセスログやメトリクス収集の土台になります。
|
||||
|
||||
## 基本の使い方
|
||||
|
||||
@@ -18,6 +18,8 @@ svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
||||
|
||||
ログコールバックには`Request`と`Response`が渡ります。メソッド、パス、ステータスコード、クライアントIP、ヘッダー、ボディなど、好きな情報を取り出せます。
|
||||
|
||||
`req.path`はパーセントデコード済みなので、CR/LFのような制御文字を含むことがあります。ログファイルに書き出す前にエスケープしてください。そうしないと、細工したリクエストでログの行を偽造されてしまいます。
|
||||
|
||||
## アクセスログ風のフォーマット
|
||||
|
||||
Apache / Nginxのアクセスログに似た形式で残す例です。
|
||||
@@ -38,6 +40,8 @@ svr.set_logger([](const auto &req, const auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
マウントポイントから配信するファイルのように、コンテンツプロバイダで送るレスポンスでは、この時点の`res.body`は空なので、サイズは`0B`になります。
|
||||
|
||||
## 処理時間を測る
|
||||
|
||||
ログで処理時間を出したいときは、pre-routingハンドラで開始時刻を`res.user_data`に保存しておき、ロガーで差分を取ります。
|
||||
@@ -48,7 +52,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>(
|
||||
@@ -59,6 +63,8 @@ svr.set_logger([](const auto &req, const auto &res) {
|
||||
});
|
||||
```
|
||||
|
||||
ロガーはレスポンスを書き出す前に呼ばれるので、この時間にボディの送信時間は含まれません。
|
||||
|
||||
`user_data`の使い方は[S12. `res.user_data`でハンドラ間データを渡す](../s12-user-data)も参照してください。
|
||||
|
||||
> **Note:** ロガーはリクエスト処理と同じスレッドで同期的に呼ばれます。重い処理を直接入れると全体のスループットが落ちるので、必要ならキューに流して非同期で処理しましょう。
|
||||
> **Note:** ロガーはリクエスト処理と同じスレッドで同期的に呼ばれ、サーバー内のすべてのロガー呼び出しが1つのロックを共有します。重い処理を直接入れると全体のスループットが落ちるので、必要ならキューに流して非同期で処理しましょう。
|
||||
@@ -43,15 +43,40 @@ svr.listen_after_bind();
|
||||
|
||||
## 戻り値のチェック
|
||||
|
||||
`bind_to_port()`は失敗すると`false`を返します。ポートが既に使われている場合などです。必ずチェックしてください。
|
||||
`bind_to_port()`は失敗すると`false`を返します。ポートにbindする権限が無い場合などです。必ずチェックしてください。
|
||||
|
||||
```cpp
|
||||
if (!svr.bind_to_port("0.0.0.0", 8080)) {
|
||||
std::cerr << "port already in use" << std::endl;
|
||||
std::cerr << "bind failed" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
`listen_after_bind()`はサーバーが停止するまでブロックし、正常終了なら`true`を返します。
|
||||
|
||||
## 使用中のポートを検出する
|
||||
|
||||
実は、デフォルトの設定では、ほかのサーバーが使っているポートにもbindできてしまいます。cpp-httplibがサーバーソケットに`SO_REUSEPORT`(Linux、macOS)か`SO_REUSEADDR`(Windows)を設定しているからです。再起動したサーバーはすぐにbindし直せます。その代わり、同じポートで2つ目のサーバーを起動してもエラーにならず、接続が両方に振り分けられます。
|
||||
|
||||
使用中のポートで`bind_to_port()`を失敗させたいときは、`set_socket_options()`でソケットオプションを差し替えてください。
|
||||
|
||||
```cpp
|
||||
svr.set_socket_options([](socket_t sock) {
|
||||
#ifdef _WIN32
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1);
|
||||
#else
|
||||
httplib::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
|
||||
#endif
|
||||
});
|
||||
|
||||
if (!svr.bind_to_port("0.0.0.0", 8080)) {
|
||||
std::cerr << "port already in use" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
`set_socket_options()`はデフォルトの設定を丸ごと置き換えます。Linux、macOSで`SO_REUSEADDR`を設定しているのは、再起動したサーバーがすぐにbindし直せるようにするためです。
|
||||
|
||||
> **Note:** Windowsでは`SO_REUSEADDR`だけでは足りません。お互いに`SO_REUSEADDR`を設定したソケット同士は、同じポートにbindできてしまいます。`SO_EXCLUSIVEADDRUSE`を使ってください。
|
||||
|
||||
> **Note:** 空いているポートを自動で選びたいときは[S17. ポートを動的に割り当てる](../s17-bind-any-port)を参照してください。こちらも内部では`bind_to_any_port()` + `listen_after_bind()`の組み合わせです。
|
||||
@@ -52,6 +52,8 @@ int main() {
|
||||
|
||||
## 処理中のリクエストの扱い
|
||||
|
||||
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに処理中のリクエストは**最後まで実行**されます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
|
||||
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに動いているハンドラは**最後まで実行**されます。ただし、ストリーミングのようにコンテンツプロバイダで送っている途中のレスポンスは、その場で打ち切られます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
|
||||
|
||||
> **Warning:** `stop()`を呼んでから`listen()`が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。
|
||||
|
||||
> **Note:** `stop()`はWebSocketハンドラを中断しません。`read()`をループで回しているハンドラは相手がつながっている限り動き続け、それが終わるまで`listen()`も戻りません。開いているWebSocket接続を記録しておき、シャットダウン時に`close()`(`CloseStatus::GoingAway`など)で閉じてください。
|
||||
@@ -10,7 +10,7 @@ status: "draft"
|
||||
|
||||
| API | デフォルト | 意味 |
|
||||
| --- | --- | --- |
|
||||
| `set_keep_alive_max_count` | 100 | 1本の接続で受け付けるリクエストの最大数 |
|
||||
| `set_keep_alive_max_count` | 100 | 1本の接続で受け付けるリクエストの最大数(0 で無制限) |
|
||||
| `set_keep_alive_timeout` | 5秒 | アイドル状態の接続を閉じるまでの秒数 |
|
||||
|
||||
## 基本の使い方
|
||||
@@ -52,6 +52,6 @@ svr.set_keep_alive_max_count(1000);
|
||||
|
||||
## スレッドプールとの関係
|
||||
|
||||
Keep-Aliveでつながりっぱなしの接続は、その間ずっとワーカースレッドを1つ占有します。接続数 × 同時リクエスト数がスレッドプールのサイズを超えると、新しいリクエストが待たされます。スレッド数の調整は[S21. マルチスレッド数を設定する](../s21-thread-pool)を参照してください。
|
||||
Keep-Aliveでつながりっぱなしの接続は、その間ずっとワーカースレッドを1つ占有します。スレッドプールは負荷に応じて最大スレッド数(デフォルトはベースの4倍)までスレッドを増やしますが、開いている接続数がそれを超えると、新しい接続はどれかが閉じるまでキューで待たされます。スレッド数の調整は[S21. マルチスレッド数を設定する](../s21-thread-pool)を参照してください。
|
||||
|
||||
> **Note:** クライアント側の挙動は[C14. 接続の再利用とKeep-Aliveの挙動を理解する](../c14-keep-alive)を参照してください。サーバーがタイムアウトで接続を切っても、クライアントは自動で再接続します。
|
||||
@@ -66,4 +66,4 @@ svr.new_task_queue = [] { return new MyTaskQueue(12); };
|
||||
#include <httplib.h>
|
||||
```
|
||||
|
||||
> **Note:** WebSocket接続はその生存期間中ずっと1スレッドを占有します。大量の同時WebSocket接続を扱うなら、動的スケーリングを有効にしておきましょう(`ThreadPool(8, 64)`のように)。
|
||||
> **Note:** WebSocket接続はその生存期間中ずっと1スレッドを占有します。大量の同時WebSocket接続を扱うなら、最大スレッド数を引き上げておきましょう(`ThreadPool(8, 64)`のように)。
|
||||
@@ -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`以外の適当な値を渡してください。
|
||||
|
||||
## クライアント側
|
||||
|
||||
|
||||
@@ -46,4 +46,4 @@ wolfSSLには商用ライセンスとサポートがあります。製品に組
|
||||
- [T03. SSL/TLSサーバーを立ち上げる](../t03-ssl-server)
|
||||
- [T05. サーバー側でピア証明書を参照する](../t05-peer-cert)
|
||||
|
||||
> **Note:** macOSでは、OpenSSL系のバックエンドを使う場合、システムのキーチェーンからルート証明書を自動で読む設定(`CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN`)がデフォルトで有効です。無効にしたい場合は`CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES`を定義してください。
|
||||
> **Note:** macOSでは、3つのどのバックエンドを使う場合でも、システムのキーチェーンからルート証明書を自動で読む設定(`CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN`)がデフォルトで有効です。無効にしたい場合は`CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES`を定義してください。
|
||||
@@ -19,6 +19,8 @@ auto res = cli.Get("/");
|
||||
|
||||
第1引数がCA証明書ファイル、第2引数がCA証明書ディレクトリ(省略可)です。OpenSSLバックエンドなら、`set_ca_cert_store()`で`X509_STORE*`を直接渡すこともできます。
|
||||
|
||||
独自のCAを指定すると、クライアントはそのCAだけを信頼し、OSの証明書ストアは読みません。両方を信頼したい場合は、`cli.enable_system_ca(true)`も呼んでください。CA証明書はクライアントの最初の接続で一度だけ読み込まれるので、これらの設定は最初のリクエストより前に済ませておきましょう。
|
||||
|
||||
## 証明書検証を無効にする(非推奨)
|
||||
|
||||
開発用のサーバーや自己署名証明書にアクセスしたいときは、検証を無効にできます。
|
||||
@@ -46,7 +48,7 @@ cli.enable_server_hostname_verification(false);
|
||||
|
||||
## OSの証明書ストアをそのまま使う
|
||||
|
||||
多くのLinuxディストリビューションでは、`/etc/ssl/certs/ca-certificates.crt`などにルート証明書がまとまっています。cpp-httplibは起動時にOSのデフォルトストアを自動で読みにいくので、普通のサーバーならとくに設定不要です。
|
||||
多くのLinuxディストリビューションでは、`/etc/ssl/certs/ca-certificates.crt`などにルート証明書がまとまっています。cpp-httplibはクライアントの最初の接続でOSのデフォルトストアを自動で読みにいくので、普通のサーバーならとくに設定不要です。
|
||||
|
||||
> mbedTLSやwolfSSLバックエンドでも同じAPIが使えます。バックエンドの選び方は[T01. OpenSSL・mbedTLS・wolfSSLの選択指針](../t01-tls-backends)を参照してください。
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ httplib::SSLServer svr(pem);
|
||||
svr.update_certs_pem(new_cert_pem, new_key_pem);
|
||||
```
|
||||
|
||||
既存の接続はそのまま、これから確立する接続は新しい証明書で動きます。
|
||||
既存の接続はそのまま、これから確立する接続は新しい証明書で動きます。差し替えは進行中のハンドシェイクが終わってから行われ(長くても読み取りタイムアウトまで)、その間に来た接続は差し替えが終わるまで待ちます。そのため、ハンドシェイク中に呼ばれるTLSのコールバックからは呼ばないでください。そのハンドシェイク自身を待ってしまいます。
|
||||
|
||||
## 証明書の準備
|
||||
|
||||
|
||||
@@ -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からクライアント証明書を設定できます。
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ for (const auto &san : sans) {
|
||||
}
|
||||
```
|
||||
|
||||
ホスト名がSANに含まれるかを確認するヘルパーもあります。
|
||||
証明書がホスト名をカバーしているかを確認するヘルパーもあります。TLSのホスト名検証と同じ規則で、IPアドレスはIPアドレスのSANと、ホスト名はDNS名のSANと照合し、CNはDNS名のSANがないときだけ使います。
|
||||
|
||||
```cpp
|
||||
if (cert.check_hostname("alice.corp.example.com")) {
|
||||
@@ -81,7 +81,7 @@ Pre-requestハンドラと組み合わせれば、共通の認可ロジックを
|
||||
|
||||
## SNI(Server Name Indication)
|
||||
|
||||
クライアントが指定してきたサーバー名は、cpp-httplibが自動で処理します。同じサーバーで複数のドメインをホストする場合にSNIが使われますが、通常はハンドラ側で意識する必要はありません。
|
||||
SNIはクライアントが自動で送ります。サーバー側では、`req.sni()`でクライアントが指定したサーバー名を取得できます。ただし`SSLServer`はその名前に関係なく同じ証明書を提示するので、1つのサーバーで複数のドメインをホストするなら、すべてのドメインをカバーする証明書を使ってください。名前ごとに証明書を切り替えたい場合は、TLSバックエンドの機能を直接使います。たとえばOpenSSLなら、コンテキストのセットアップ用コールバックを受け取る`SSLServer`のコンストラクタで、servernameコールバックを設定します。
|
||||
|
||||
> **Warning:** `req.peer_cert()`は、mTLSが有効で、かつクライアントが証明書を提示した場合のみ有効な値を返します。通常のTLS接続では空の`PeerCert`が返ります。使う前に必ず`bool`チェックしてください。
|
||||
|
||||
|
||||
@@ -21,7 +21,12 @@ int main() {
|
||||
if (result == httplib::ws::ReadResult::Fail) {
|
||||
break;
|
||||
}
|
||||
ws.send(msg); // 受け取った内容をそのまま返す
|
||||
// 受け取った内容を同じフレームタイプでそのまま返す
|
||||
if (result == httplib::ws::ReadResult::Binary) {
|
||||
ws.send(msg.data(), msg.size());
|
||||
} else {
|
||||
ws.send(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -29,13 +34,14 @@ int main() {
|
||||
}
|
||||
```
|
||||
|
||||
`svr.WebSocket()`でWebSocket用のハンドラを登録します。ハンドラが呼ばれた時点で、すでにWebSocketのハンドシェイクは完了しています。ループの中で`ws.read()`して`ws.send()`するだけで、エコー動作が完成します。
|
||||
`svr.WebSocket()`でWebSocket用のハンドラを登録します。ハンドラが呼ばれた時点で、すでにWebSocketのハンドシェイクは完了しています。ループの中で`ws.read()`して`ws.send()`するだけで、エコー動作が完成します。バイナリメッセージは`data()`と`size()`を渡すオーバーロードで返すので、バイナリのまま届きます(詳しくは後述)。
|
||||
|
||||
`read()`の返り値は`ReadResult`列挙値で、次の3種類です。
|
||||
`read()`の返り値は`ReadResult`列挙値で、次の4種類です。
|
||||
|
||||
- `ReadResult::Text`: テキストメッセージを受信
|
||||
- `ReadResult::Binary`: バイナリメッセージを受信
|
||||
- `ReadResult::Fail`: エラー、または接続が閉じた
|
||||
- `ReadResult::Timeout`: `set_read_timeout()`で自分が設定した読み取りタイムアウトが、何も受信しないまま経過した。接続は開いたまま。コンパイル時のデフォルトのタイムアウトは接続を閉じ、`Fail`として返る([W06. タイムアウトを設定する](../w06-websocket-timeouts)を参照)
|
||||
|
||||
## クライアント: エコーを叩く
|
||||
|
||||
@@ -75,7 +81,7 @@ ws.send(binary_data, binary_data_size); // バイナリフレーム
|
||||
|
||||
## スレッドとの関係
|
||||
|
||||
WebSocket接続はハンドラが終わるまで生き続けるので、1接続につきワーカースレッドを1つ占有します。同時接続数が多い場合は、スレッドプールを動的スケーリングに設定しましょう。
|
||||
WebSocket接続はハンドラが終わるまで生き続けるので、1接続につきワーカースレッドを1つ占有します。デフォルトのスレッドプールも負荷に応じてベースの4倍まで増えますが、同時接続数が多い場合は、その最大スレッド数を引き上げましょう。
|
||||
|
||||
```cpp
|
||||
svr.new_task_queue = [] {
|
||||
|
||||
@@ -41,9 +41,9 @@ cli.connect();
|
||||
|
||||
デフォルトのPing間隔は、ビルド時のマクロ`CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`で決まります。通常はそのままで問題ありませんが、特別なプロキシ環境に合わせて短くしたい場合は調整してください。
|
||||
|
||||
## PongはどうやってpIngに応答するか
|
||||
## Pingへの応答(Pong)
|
||||
|
||||
WebSocketプロトコルでは、PingフレームにはPongフレームで応答することが決まっています。cpp-httplibは受信したPingに自動でPongを返すので、アプリケーションコード側で気にする必要はありません。
|
||||
WebSocketプロトコルでは、PingフレームにはPongフレームで応答することが決まっています。cpp-httplibは受信したPingに`read()`の中で自動でPongを返すので、`read()`を呼び続けている限り、アプリケーションコード側で気にする必要はありません。
|
||||
|
||||
## Pingの間隔をどう決めるか
|
||||
|
||||
@@ -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_READ_TIMEOUT_SECOND`(デフォルト**300秒 = 5分**)が保険として働き、フレームが一定時間来なければ`read()`が失敗します。つまり`max_missed_pongs`は「**もっと速く**無応答を検出したい」ときに使うオプションだと考えてください。
|
||||
サーバー側は`0`のままでも接続が残り続けることはありません。ハンドラが`read()`を呼んでいる間は`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`(デフォルト**300秒 = 5分**)が保険として働きます。一方クライアント側にはこの保険がなく、読み取りタイムアウトを設定しない限り無期限に待つので、無応答ピアを検出する手段は`max_missed_pongs`だけです。どちらの側でも「**もっと速く**検出したい」ときに使うオプションでもあります。
|
||||
|
||||
> 接続が閉じたときの処理は[W03. 接続クローズをハンドリングする](../w03-websocket-close)を参照してください。
|
||||
@@ -67,7 +67,7 @@ cli.close(httplib::ws::CloseStatus::Normal);
|
||||
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
||||
```
|
||||
|
||||
クライアント側はこのステータスを見て、再接続を試みるかどうかを判断できます。
|
||||
クライアント側の`read()`は`Fail`を返すだけで、受け取ったステータスや理由は取り出せません。再起動による切断をほかの切断と見分けたい場合は、先にメッセージ(`ws.send("restarting")`など)を送ってから`close()`を呼びましょう。
|
||||
|
||||
## サンプル: 簡単なチャット終了
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ switch (result) {
|
||||
case httplib::ws::ReadResult::Fail:
|
||||
// エラーまたは切断
|
||||
break;
|
||||
case httplib::ws::ReadResult::Timeout:
|
||||
// 読み取りタイムアウト。接続は開いたまま
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -82,4 +85,4 @@ if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
|
||||
|
||||
テキストとバイナリを混ぜて送ることもできます。たとえば「制御メッセージはJSON、データ本体はバイナリ」といったプロトコルを組み立てると、メタデータと生データを効率よく扱えます。
|
||||
|
||||
> **Note:** WebSocketのフレームサイズには上限がないわけではありません。巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。cpp-httplibのデフォルトでは大きなフレームもそのまま処理されますが、メモリを一気に使う点は変わりません。
|
||||
> **Note:** 受信できるメッセージの大きさは`CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH`(デフォルトは16MB、0なら無制限)までです。これを超えると`read()`は`Fail`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user