Compare commits

..
82 Commits
Author SHA1 Message Date
yhirose c419c904da Release v0.61.0 2026-10-13 22:56:02 -04:00
yhirose 878ba41099 Wait for the reconnect in the SSE retry test instead of sleeping
SSEIntegrationTest.DigitRetryFieldApplied slept for 500ms and then
expected a second connection. The first connection, the 100ms wait and
the reconnect do not always fit in that window: the macOS Mbed TLS job
saw only one connection.

Wait until the second connection arrives, and check that it came at
least 100ms after the first one rather than counting connections. The
test no longer depends on how fast the runner is, and takes about 150ms
instead of 500ms.
2026-10-13 09:07:56 -04:00
yhirose 941745c33d Send proxy Basic authentication when one credential is empty
Proxy-Authorization was added only when both the proxy username and the
proxy password were set, and a cross-host redirect carried the proxy
credentials over only when the username was set. Authorization has been
sent when either one is set since #958; do the same for the proxy.

A client that has both a proxy Basic credential with one empty field
and a proxy bearer token now sends Basic rather than Bearer, the order
Authorization already follows.
2026-10-12 22:59:55 -04:00
yhirose 11daa99c86 Stop at the last match when getting a value by index
get_header_value(), get_header_value_u64(), get_multimap_value() and
MultipartFormData::get_field() advanced an equal_range() iterator by
the caller's index after casting it to ssize_t. An index that is
negative as a signed value stepped back onto an entry of another key,
and a huge positive one kept looping after the last match.

Advance with bounded_next(), which stops at the end of the range.
2026-10-12 22:59:55 -04:00
yhirose cbaf751da1 Ignore quoted-strings when parsing an Accept header
parse_accept_header() split on every ',' and then on every ';', with no
idea that a parameter value can be a quoted-string (RFC 9110 §5.6.6). A
value such as text/html;profile="a,b" was cut in the middle, and the
request was answered with 400.

The parser never looks at a parameter value, so remove each
quoted-string (§5.6.4) before parsing rather than teach every split
about quotes. A header without a '"' takes the same path as before.

A quoted-string is removed wherever it appears, so a malformed value
can now be read without it instead of being rejected, and an
unterminated quote hides the rest of the value.
2026-10-12 22:59:47 -04:00
yhirose 33d84a12b6 Compare the Range unit case-insensitively
RFC 9110 §14.1 makes range unit names case-insensitive, but
parse_range_header() matched "bytes=" exactly, so a request with
Range: Bytes=1-3 was answered with 416.
2026-10-12 19:37:07 -04:00
yhirose 5107381963 Fix the RFC reference in the Host validation test
The rule that a client sends an empty Host value when the target URI
has no authority is in RFC 9112 §3.2, not RFC 9110 §7.2.
2026-10-11 23:44:07 -04:00
yhirose 0acbee16dc Reject an ambiguous or invalid Host in a request
A request with more than one Host field line, or with a Host value
holding a byte that cannot appear in uri-host [ ":" port ], is now
answered with 400 (RFC 9112 §3.2). The handler sees only the first
Host line, so such a request could reach it with an authority that
differs from the one an intermediary acted on.

Only the byte set is checked, not the full grammar. An empty value
stays valid, and a request without a Host line is still accepted.

Close #2623
2026-10-11 23:39:50 -04:00
yhirose 1f12bbaabb Treat a bare CR as an SSE line ending
The SSE spec ends a line with CRLF, LF or CR, but SSEClient split only
on LF, so a stream that uses CR alone never produced an event. The LF
of a CRLF is skipped even when it arrives in a later chunk than its CR.

Search for a line ending only in the newly received data. What is left
in the buffer has none, and scanning it again for every chunk made a
long line quadratic.
2026-10-11 23:05:46 -04:00
yhirose 5189edc52e Ignore an SSE id that cannot be sent as Last-Event-ID
SSEClient stored any id it received, but the client rejects a request
whose header value is invalid. An id with a NUL, a control character or
surrounding whitespace therefore made every reconnect fail with
Error::InvalidHeaders before reaching the server, and the id could
never be replaced.

Accept an id only if it is a valid header value, so that the previous
id stays in effect. The SSE spec asks for this for NUL only; the rest
follows from what this client can send.
2026-10-11 23:05:38 -04:00
yhirose fee592c2c2 Ignore a leading UTF-8 BOM in an SSE stream
The SSE spec strips one BOM at the start of the stream, but
SSEClient kept it as part of the first field name, so the
first event was silently dropped.
2026-10-08 21:07:40 -04:00
yhirose 885ed54b10 Unify spacing and wording in the Japanese docs pages
Drop the spaces between Japanese text and inline code or alphanumerics
in the tour and the few other pages that still had them, and reword
sentences that read awkwardly. The client compression page now lists
Zstd alongside zlib and Brotli.
2026-10-08 20:39:13 -04:00
yhirose c95d799180 Polish the wording of the updated docs pages
Reword the Japanese sentences so they read naturally, and correct the
size of the llama.cpp server sources in the code reading chapter.
2026-10-08 20:39:13 -04:00
yhirose bef278e0d2 Fix docs pages that no longer match the code
Samples that did not compile or run as shown:
- res.user_data.get<T>() inside a generic lambda needs the `template`
  keyword; use explicit parameter types (tour 09, cookbook s15).
- listen() on a Unix domain socket fails with port 0 (tour 09, s22).
- "*.dev.local" is not a NO_PROXY pattern (c16).
- ssl_backend_error() holds a verify result, not an ERR_get_error()
  value, after a verification failure; decode each with the matching
  OpenSSL function (c18).
- The content provider's `length` is everything that remains, so the
  sample read the whole file in one call (s05).

Statements corrected:
- Client keep-alive is off by default; c14 is rewritten around
  set_keep_alive(true).
- Mounted files are looked up before GET handlers (tour 04, s04).
- Params keep insertion order, and to_string(Error::Connection) reads
  "Could not establish connection" (tour 02).
- A chunked provider ends with sink.done(), and post_routing_handler
  runs before the response is sent (tour 09).
- Timeouts surface as Error::Read; Error::Timeout comes from the stream
  API (c17). The max timeout cuts off the wait for the response only
  (c13). The progress callback needs Content-Length (c11).
- Encoding selection follows q-values, then Brotli, gzip, Zstd (s08),
  and the client compresses with the first of those it was built with
  (c15).
- stop() cuts a provider-driven response short (s19); a rejected
  content_reader already gets 400 or 413 (s07); user_data values must be
  copyable (s12); Client accepts a client certificate too (t04);
  on_message() is the fallback for every unhandled event and 204/403/404
  end reconnection (e04); the pong timeout takes two to three intervals
  and ends a waiting read() (w02).

In the LLM app tutorial, an uncaught exception does not crash the
server, so say what it does instead. Drop the server and client timeout
settings whose stated purpose, covering inference and download time,
they do not serve: those timeouts bound a single socket wait. Update
the llama.cpp server layout in chapter 7.
2026-10-08 20:39:13 -04:00
yhirose 05f7478523 Fix README samples and statements that no longer match the code
Samples that did not compile or did not do what they showed:
- SSLServer has no default constructor, and SSLClient("host:port") does
  not parse the port.
- res.user_data.get<T>() inside a generic lambda needs the `template`
  keyword; use explicit parameter types instead.
- get_header_value() takes the default value before the index.
- Server has no socket(); show set_socket_opt inside set_socket_options.
- The content provider sample used a local without capturing it.
- "*.dev.local" is not a NO_PROXY pattern; ".dev.local" is.
- The reverse proxy example in README-stream.md called open_stream()
  without a method and moved a StreamHandle into a std::function. Keep
  the client and the handle in one shared object.
- open_stream() does not follow redirects, so drop set_follow_location()
  from the Stream API samples.

Statements corrected:
- ssl_error() returns a tls::ErrorCode, not SSL_ERROR_*.
- An exception escaping the exception handler no longer crashes the
  server; the connection is dropped and the error logger is told.
- post_routing_handler runs before every response, including those the
  earlier hooks short-circuit; file_request_handler runs for GET only.
- Only wolfSSL cannot enumerate CAs loaded from a path or the system.
- Digest authentication and the WebSocket TLS setters need any TLS
  backend, not OpenSSL specifically.
- A dynamic pool thread exits on the idle timeout only.
- The stream connection closes when the Result is destroyed.
- The pong timeout takes two to three ping intervals to fire.
- Regex routes skip paths over CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH.

Also list the Error values and compressible MIME types that were
missing, note that a content receiver lifts the default client payload
limit, and update the docker server's startup output.
2026-10-08 20:39:13 -04:00
yhirose f6aee694e2 Log the response length for static files in the docker server
The access log took $body_bytes_sent from res.body, which stays empty
for a static file because it is sent by a content provider. Every file
was logged as 0 bytes. Use the Content-Length of the response instead,
and 0 for HEAD.
2026-10-08 20:39:13 -04:00
yhirose 8aa547e4a1 Wake a blocked WebSocket read when the pong timeout fires
When max_missed_pongs was exceeded, the heartbeat thread called close(),
which returns without touching the socket while another thread is in
read(). That read() then stayed blocked until its read timeout: forever
by default on a client, 300 seconds on a server. A plain read loop never
noticed the unresponsive peer the heartbeat had just detected.

Shut down the read side of the socket after close() so the pending
read() returns Fail. Only the read side: a TLS backend answers the EOF
with an alert, and writing it to a socket closed for writing raises
SIGPIPE in a process that has not ignored it.

ClientDetectsNonResponsivePeer now waits in read() instead of polling
is_open(), which covers both.
2026-10-08 20:39:13 -04:00
yhirose 84ff13ec47 Treat a payload max length of 0 as unlimited on every read path
set_payload_max_length(0) is documented to disable the limit, but the
readers for a chunked body and for a body delimited by the connection
closing compared the size against the limit without checking for 0.
A server configured that way answered a chunked request with 413, and
a client failed to read a chunked or unframed response. A body with
Content-Length was already unlimited.

Give both readers the same `payload_max_length > 0` guard the other
payload checks use.
2026-10-08 20:39:13 -04:00
metsw24-maxandyhirose 8f094fe292 match a wildcard only in the leftmost label in match_hostname (#2619)
* match a wildcard only in the leftmost label in match_hostname

* Shorten the wildcard comment in match_hostname

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-10-08 12:47:24 -04:00
yhirose 00afaaed6a Release v0.60.1 2026-10-07 23:40:36 -04:00
yhirose e803f5e413 Let the SSL chain policy alone judge the Windows chain (#2618)
verify_cert_with_windows_schannel() rejected a chain whenever
TrustStatus.dwErrorStatus was non-zero, before
CertVerifyCertificateChainPolicy() ran. The
CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS flag passed to that
policy check was therefore dead code: a certificate without revocation
information, or one whose CRL could not be fetched, failed with
CERT_TRUST_REVOCATION_STATUS_UNKNOWN.

Drop the pre-check so the SSL chain policy is the only judge.
Revocation checking becomes best-effort: a revoked certificate and
every other chain error are still rejected, while an undetermined
revocation status is accepted.

On a rejected chain, ssl_backend_error() now holds the policy status,
such as CERT_E_UNTRUSTEDROOT, instead of the trust status bit mask.
2026-10-07 23:19:36 -04:00
Michael Weitzel 57b8aca6da Avoid name clash with class WebSocketClient by explicit qualification (#2616)
Adds an explicit namespace qualification and a forward declaration for
class WebSocketClient. This change avoids a name clash on code bases
containing unrelated WebSocketClient classes.
2026-10-07 22:38:50 -04:00
KBSandyoudie006 213029685a Serve the whole body for a suffix range longer than it (#2615)
RFC 9110 14.1.2: if the representation is shorter than the suffix-length,
the entire representation is used. range_error computed a negative first
byte position for bytes=-8 on a 7-byte body and answered 416. Clamp it
at 0, as #711 did before the range handling was reworked.

Co-authored-by: youdie006 <youdie006@users.noreply.github.com>
2026-10-07 22:20:53 -04:00
yhirose 17eeb18feb Release v0.60.0 2026-10-06 22:57:42 -04:00
metsw24-maxandyhirose edc9760005 use the SAN type tag in Mbed TLS verify_hostname and get_cert_sans (#2614)
* use the SAN type tag in Mbed TLS verify_hostname and get_cert_sans

Mbed TLS keeps a subjectAltName entry's GeneralName tag in buf.tag and the bare value in buf.p / buf.len. verify_hostname ignored the tag, so a dNSName whose bytes equal an address authenticated that IP host, and an iPAddress or rfc822Name was matched as a DNS pattern. get_cert_sans looked for the tag inside the value, so it reported no entries for an ordinary certificate, or part of a dNSName as an entry of its own.

* Shorten the SAN type comments

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-10-05 21:13:50 -04:00
yhirose 6d1049462d Ignore a subprotocol the WebSocket client did not offer
A SubProtocolSelector could return a value outside the client's
Sec-WebSocket-Protocol list, and the server sent it back as is. The
server now treats such a value as no selection.
2026-10-04 18:34:21 -04:00
metsw24-maxandyhirose 4fcbc08f2d reject an unoffered subprotocol in read_websocket_upgrade_response (#2595)
* reject an unoffered subprotocol in the ws client handshake

* test the subprotocol check through WebSocketClient so the split build compiles

* Trim comments in the subprotocol check

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-10-04 18:21:39 -04:00
Jordan Woyak d59f3e438c Remove semantically redundant closed_ checks in ping thread. (#2613) 2026-10-04 09:39:24 -04:00
yhirose 09fa6820fe Fix 303 redirect request bodies and Location path decoding (Fix #2606, #2607)
A 303 response turns the follow-up request into a GET, but only the buffered body and headers were cleared. A content provider (sized or chunked) stayed on the request, so the original payload was sent again, and for a chunked provider the unframed chunks also broke the keep-alive connection.

The redirect also percent-decoded the Location path before sending it. That turned %23, %3F and %25 into a fragment, a query delimiter and a different octet, so the client requested a different resource than the one named, and made set_path_encode(false) fail on any Location containing %20. The path is now sent as given.
2026-10-03 19:06:45 -04:00
yhirose 438319cfcb Fix WebSocket pings being sent early on spurious wakeups
The heartbeat thread waited on ping_cv_ without a predicate, so a
spurious wakeup ended the wait early and sent a ping before
ping_interval_sec_ had elapsed. With max_missed_pongs enabled, the
early ping also counted toward the pong timeout.

Pass a predicate to wait_for so that the wait only ends when the
interval elapses or the connection is closed.

Reported in #2612.
2026-10-03 17:47:30 -04:00
yhirose eda9a10bfe Fix SSE client not clearing Last-Event-ID on an empty id field (Fix #2611)
An event with an empty id field must reset the last event ID, so that
no Last-Event-ID header is sent on reconnect. run_event_loop only
updated last_event_id_ when the id was non-empty, so it could not tell
an empty id field from an event with no id field, and kept sending the
stale ID.

Track whether an id field was seen with a has_id flag, as has_data
does for the data field, and add a regression test.
2026-10-03 17:29:33 -04:00
yhirose cf3693cb5c Release v0.59.0 2026-10-02 22:06:39 -04:00
yhirose 4fd9ae8f42 Serve pipelined requests without waiting for the keep-alive timeout
A client may pipeline its requests (RFC 9112 9.3.2). The server read the
following request(s) into a per-request SocketStream buffer, discarded them
with the stream after the first response, and then waited in keep_alive()
for socket data that never came, closing the connection after the
keep-alive timeout. Over TLS the bytes stayed decrypted in the TLS library,
where keep_alive() could not see them either.

Create one stream per connection and serve a request that is already
buffered (Stream::is_readable()) without waiting in keep_alive().

Keeping the buffer means an extra CRLF that some clients send after a
request body is now parsed as the next request line, which answered 400
and closed the connection. Ignore one empty line before the request-line,
as RFC 9112 2.2 recommends.

Fixes #2599
2026-10-02 21:47:18 -04:00
yhirose 3d40dfc727 Fix SSE parsing of CRLF field names and data-less events
A field line without a colon kept the \r of a CRLF line ending in its
name, so "data\r\n" was not recognized. Strip the \r once per line
before parsing instead of from each value.

An event without a data field was neither dispatched nor cleared, so
its event type leaked into the next event and its id only reached
last_event_id after a later event was dispatched. Reset the message on
every blank line and record the id even when nothing is dispatched.

The parsing tests exercised a copy of parse_sse_line that had drifted
from the real one. Run them through SSEClient against a local server
instead, and add regression tests for the cases above.
2026-10-02 21:38:39 -04:00
metsw24-max dd71728110 escape quoted-string auth-params in make_digest_authentication_header (#2597) 2026-10-02 21:29:35 -04:00
DosX 7255a7e979 Preserve empty SSE data fields (#2594)
SSE events may contain an empty data field, and a data field without a colon also has an empty value. Track whether a data field was seen separately from the accumulated payload so empty events are dispatched and leading empty lines are preserved. Add an integration regression test for both forms.
2026-10-02 21:17:47 -04:00
yhirose 8a3abfb597 Extract parse_int_in_range from parse_port
parse_port and the NO_PROXY CIDR prefix parsing each repeated the same
from_chars call, full-consumption check and range check. Move that into
a parse_int_in_range helper and use it in both places.
2026-10-02 21:15:14 -04:00
KBS 10aadd57f7 Reject trailing characters in URL port numbers (#2593)
parse_port checked only the error code of from_chars, which stops at
the first non-digit, so http://host:80abc was accepted as port 80, and
a redirect Location with such a port was followed. RFC 3986 defines
port as *DIGIT. Require the whole string to be consumed, as #2590 does
for quality values.
2026-10-02 21:07:34 -04:00
yhirose 43863e1f67 Make CryptoAPI the only chain verifier when Windows verification is on (#2604)
Every backend loads the Windows ROOT and CA stores, but Windows adds a
root to them only when CryptoAPI needs it to build a chain. On a machine
that had not needed a root yet, the backend rejected the chain before
the CryptoAPI check ran, so Windows never fetched the root (for example
OpenSSL error 20 for accounts.spotify.com under Starfield Root G2).

With Windows verification enabled, the backend's chain verdict is no
longer used. Mbed TLS and wolfSSL skip chain verification during the
handshake, and the post-handshake verify result is ignored. The
CryptoAPI check becomes mandatory: a leaf that cannot be encoded now
fails the connection instead of skipping the check, and the chain must
allow server authentication, which the backends used to check.

A server certificate verifier works on the backend's chain verification,
so when one is set the backend still decides and CryptoAPI only adds its
own check, as before.

ClientCertMissing now disables hostname verification: cert.pem does not
match HOST, and on Windows the hostname check fails before the chain
check.

Refs #2596
2026-10-02 20:48:47 -04:00
yhirose 0db1df7cf2 Pass the server's intermediates to Windows certificate verification (#2602)
CryptoAPI got only the leaf, so it fetched an issuer from the leaf's AIA
URL instead of using the intermediates the server sent. For
accounts.spotify.com that issuer chains to Certainly Root R1, which
Windows does not trust, while the server's own chain ends at Starfield
Root G2.

Add tls::get_peer_certs(), which returns the certificates the peer sent
in the same way get_ca_certs() returns the CA certificates, for every
backend. The CryptoAPI check puts them into a memory store that it
passes to CertGetCertificateChain(), skipping any certificate that
cannot be added. wolfSSL keeps the received chain only when built with
SESSION_CERTS; without it, CryptoAPI still gets the leaf alone.

Refs #2596
2026-10-02 20:48:10 -04:00
yhirose 639391ad7f Reject an invalid Content-Length and honor Connection: close
A request whose Content-Length was present but not a valid decimal length
(e.g. "42, 42", "+42", "0x2e" or empty) was treated as having no body
unless a handler read it: no 400 was returned, the body was not drained,
and the bytes after the header block were parsed as the next request on
the keep-alive connection. Reject such a request with 400 and close the
connection before routing, as RFC 9112 Section 6.3 requires.

The server also kept reading after a response that announced
Connection: close. A rejected request line or header block left the rest
of the message to be parsed as a new request, and an error response to a
bodyless request did the same with whatever followed. Close the
connection whenever the final response carries Connection: close
(RFC 9112 Section 9.6), and mark the two request-head rejection paths
closed explicitly as the other rejection paths already do.
2026-10-02 00:22:24 -04:00
yhirose 0715c2739e Enforce a minimum SSE reconnect wait to avoid a busy loop (#2592)
SSEClient::wait_for_reconnect() sleeps in 100ms steps until the
reconnect interval has elapsed. With an interval of 0 (for example
"retry: 0" from the server, or set_reconnect_interval(0)) it never
slept at all, so a server that sends "retry: 0" and closes the stream
made the client reconnect in a tight loop. set_max_reconnect_attempts()
does not stop this either, because each successful connection resets
the attempt counter.

Always wait at least one step (100ms). Intervals of 1-99ms already
waited 100ms because of the step size, so only 0 and negative values
change behavior.
2026-09-28 17:25:37 -04:00
KBS 3330d0eb06 Ignore an SSE retry field that is not all digits (#2591)
parse_sse_line checked only the error code of from_chars, which accepts
a leading '-' and stops at the first non-digit, so retry: -1 made the
client reconnect without waiting and retry: 10s set 10 ms. The SSE spec
ignores a retry value that is not all ASCII digits.
2026-09-28 15:31:20 -04:00
yhirose c1c2b1f4b4 Apply the request-target check to the client and encode control chars
Share the server's request-target check as fields::is_request_target()
and use it in write_request_line too. The client previously used
is_field_value(), which let an embedded SP or HTAB through.

encode_path() only escaped CR/LF among the control characters, so with
path encoding enabled a path like "/a\tb" would now be rejected instead
of sent. Percent-encode every control character (0x00-0x1F, 0x7F).
2026-09-28 03:37:11 -04:00
yhirose e11dbec7b3 Reject control characters in the request-target
RFC 9112 §3.2 does not allow control characters in the request-target,
and §2.2 requires a bare CR to be treated as invalid. parse_request_line
accepted them, so e.g. "GET /a\rb HTTP/1.1" was routed normally. Reject
any byte that is not VCHAR or obs-text with 400 Bad Request. obs-text is
still allowed since some clients send raw UTF-8 in the target.
2026-09-27 23:35:09 -04:00
yhirose 174bce5ccf Escape request data in the docker server's access and error logs
req.path is percent-decoded, so a request like GET /%0D%0A... put a
literal CR/LF into the NGINX-style log lines and let a client forge
extra entries. Log the raw req.target (matching NGINX's $request) and
escape '"', '\', control and non-ASCII bytes as \xHH the way NGINX
does. Also note in the README logging section that req.path may
contain control characters and should be escaped before logging.
2026-09-27 22:50:26 -04:00
DosX 57c4f7f385 Reject trailing characters in HTTP quality values (#2590)
parse_quality accepted values such as q=0.5junk because it checked only the conversion error and ignored the returned end pointer. Require the numeric parser to consume the complete q parameter so malformed Accept values are rejected and invalid Accept-Encoding weights are ignored. Add regression cases for both headers.
2026-09-27 19:20:14 -04:00
yhirose 2fb2dbbe1e Send small static files with the headers and large bodies without a copy (#2589)
A file served from a mount point or through set_file_content() left in two
writes, one for the status line and headers and one for the body, because the
body came from a content provider. A small file is now read into the header
buffer so the whole response leaves in a single write. Only file-backed
providers are coalesced this way: a user-supplied provider may produce its data
over time, and holding the headers back until it finishes would stall the
client.

A large set_content() body was copied into the header buffer before being
sent. A body of CPPHTTPLIB_SEND_BUFSIZ or more is now written directly after
the headers, which saves the copy at the cost of one extra write.
2026-09-26 22:19:15 -04:00
VecSzn 8b6ab24159 Resolve relative Location references on redirect (#2586) 2026-09-26 19:49:21 -04:00
Tobias WallnerandTobias Wallner 5a202d3d5f Added a feature test to auto enable/disable CPPHTTPLIB_USE_NON_BLOCKI… (#2578)
* Added a feature test to auto enable/disable CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO

* turned status: WARNING 'GetAddrInfoExCancel is unavailable; disabling non-blocking getaddrinfo.' into a warning

* added ws2_32 for the GetAddrInfoExCancel. this catches previous false negatives

---------

Co-authored-by: Tobias Wallner <tobias.wallner@qtlabs.at>
2026-09-25 15:20:00 -04:00
yhirose 4f3f9ef19b Release v0.58.0 2026-09-21 20:01:43 -04:00
yhirose 6d59d1e2df Build open_stream's request head in memory before sending
open_stream wrote the request line and each header straight to the
socket, so a header rejected by check_and_write_headers left the request
line and the headers before it on the wire. Build them in a BufferStream
first and flush once, as write_request and the WebSocket handshake do.
2026-09-21 19:15:39 -04:00
yhirose 9386b25dd7 Don't wait for a response to a request rejected before sending
process_request reads the response even after write_request fails, so
that an early response (e.g. 413/414) sent while the body is still being
uploaded is not lost. A request line or header rejected while the
request is being built in memory never reaches the socket, though, so
no response will come and the client blocked until the read timeout (or
until the server closed the idle connection).

write_request now reports such a local rejection, and process_request
returns immediately in that case. Socket write failures still read the
response as before.
2026-09-21 19:15:30 -04:00
yhirose 91c55a4385 Release v0.57.1 2026-09-21 12:47:22 -04:00
yhirose ad88645a83 Reject non-token methods in write_request_line
write_request_line checked the request target for CR/LF but concatenated
the method verbatim. A method carrying CR/LF could smuggle a whole
request ahead of the real one, and the client would take the smuggled
request's response as its own. A method with a space or an empty method
put a malformed request line on the wire.

Require the method to be a token (RFC 9110 Section 9.1) before anything
is written. All three callers (the buffered client path, open_stream and
the WebSocket handshake) go through this function and fail with
Error::Write, as they already do for a rejected target.

Claude-Session: https://claude.ai/code/session_01NTDesJQTQPEuu4o4XCu69g
2026-09-21 12:25:12 -04:00
yhirose 82722fcb13 Release v0.57.0 2026-09-20 20:38:01 -04:00
metsw24-maxandyhirose 8b872605e0 reject control characters in chunk extensions in read_payload (#2585)
* reject control characters in chunk extensions in read_payload

* Bound every chunk-size line scan by the line terminator

read_payload() ended its scans of one line buffer two different ways: the
hex-size parse and the space skip that follows stopped on the NUL that
stream_line_reader::append() writes, while the new chunk-ext check walked
to an explicit end pointer. Compute that end pointer first and bound all
of them by it, so no scan depends on the buffer's NUL and the terminator
can never be read as line content.

The bare-LF branch is reachable only under
CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR, where getline() ends the line on
an LF that is the terminator rather than extension text. Say so: the
comment below it explains why a bare LF inside the line is rejected, and
without that note the two read as contradictory. Its guard no longer
depends on the scan cursor either, since all it ever needed was a check
that there is a byte to look at.

* Reuse the chunked-body helper in the chunk-ext acceptance test

AcceptsChunkExtension repeated expect_chunked_body_rejected()'s body
verbatim apart from the expected status, so parameterise the helper on
the status and keep the rejection wrapper for the existing callers. The
decoded body is already checked by the /chunked handler, so asserting
the status is all the new test needs.

Also record why the control-character literal stays split: a hex escape
consumes every hex digit that follows it, so "\x01b" would be the single
byte \x1b rather than \x01 followed by 'b', and joining the halves would
quietly change what the test sends.

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-09-20 20:22:52 -04:00
yhirose 52f214bf2e Don't wait for the peer's close_notify on OpenSSL shutdown
tls::shutdown() on OpenSSL called SSL_shutdown() a second time to wait
for the peer's close_notify. An idle keep-alive client never sends one,
so closing its connection held the worker thread until the read timeout,
and Server::stop() waited for it. Send close_notify and return, as the
Mbed TLS and wolfSSL backends already do.
2026-09-19 17:28:09 -04:00
yhirose 09c02f1335 Send 100 Continue only when the request body is read
The server wrote 100 Continue as soon as it saw the expectation, before
pre_routing_handler, pre_request_handler, or routing ran. A request
those handlers rejected, or one that matched no route, still invited
the client to send a body the server would never read.

Defer the interim response until the body is about to be read. If the
request is answered without reading the body, 100 Continue is never
sent and the connection is closed, since whether and when the client
sends the body is unknown.

Also treat a 417 returned by expect_100_continue_handler as the final
response. It used to be written as a bare status line, after which the
request was processed and a second response was written.
2026-09-19 17:28:09 -04:00
yhirose 2e5480ad65 Document that pre_request_handler runs for WebSocket routes 2026-09-19 17:28:09 -04:00
yhirose 4cb363e3f2 Run pre_request_handler for WebSocket routes
The WebSocket upgrade path matched the route and switched protocols
without setting req.matched_route or calling pre_request_handler, so a
check placed there (e.g. authentication) never ran for WebSocket
routes. Set matched_route and run the handler before the upgrade; if it
handles the request, reply with a regular HTTP response instead of 101.

Also write rejected upgrade responses (from pre_routing_handler too)
with write_response_with_content, so they carry Content-Length. Without
it, a client reading the body waited until the keep-alive timeout.
2026-09-19 17:28:09 -04:00
yhirose deb520e26b Update version files with sed -i.bak, which GNU sed accepts too
`sed -i ''` is BSD-only: GNU sed takes the '' as the script and the expression as a file name, so `just release --run` failed on Linux before touching anything.
2026-09-19 13:56:31 -04:00
yhirose f37a5b1407 Fix #2583 2026-09-14 17:31:07 -04:00
yhirose f15992c7ed Update documentation 2026-09-14 12:27:52 -04:00
yhirose 278c2979e8 Release v0.56.0 2026-09-11 17:35:54 -04:00
yhirose 6b8c3f5387 Report only a caller-set WebSocket read timeout as Timeout
199d7ee made read() return the new ReadResult::Timeout for every read
timeout and leave the connection open. The compile-time server default
(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 300s) is always in
effect, so a handler written as `while (ws.read(msg))`, the form the
README's Quick Start uses, no longer ended when a peer went quiet:
Timeout is non-zero, so the loop ran its body again with the previous
message still in `msg`, and the worker the backstop is meant to reclaim
was never released. Nothing caught it because every test of the new
result set a timeout explicitly and checked the result by value, and the
heartbeat tests keep the connection alive with pings.

The two timeouts mean different things. One the caller sets through
set_read_timeout() is a request for control back, and is reported as
Timeout on a still-open connection. The compile-time default is a
backstop against a peer that has gone quiet, and elapsing it is now a
failure again: read() returns Fail and closes the connection, as it did
before 199d7ee. WebSocket tracks whether set_read_timeout() was called,
and WebSocketClient carries the same flag over to the WebSocket it
creates on connect().

Tests use the heartbeat binary, which compiles both defaults down to 3s:
a `while (ws.read(msg))` server handler runs its body once and exits
when the client falls silent, and a client that never set a timeout gets
Fail with the connection closed. The README and cookbook now say which
timeout produces Timeout.

Claude-Session: https://claude.ai/code/session_01EF5uZ1X2kaHhqJ8VgfjVaQ
2026-09-11 17:29:20 -04:00
yhirose e640f8376b Release v0.55.0 2026-09-11 16:54:08 -04:00
yhirose 73a4092f8a Point the remaining httpbingo.org proxy tests at the self-hosted httpbin
ProxyTest, RedirectTest.HTTPBin*, KeepAliveTest and ProxyTest.SSLOpenStream
still sent their requests through the squid proxies to the external
httpbingo.org, so an upstream hiccup there failed CI with no code change
involved (KeepAliveTest.SSLWithDigest got a 502 on its first /get).

Switch them to the "httpbin" container (nginx + go-httpbin) that
BaseAuthTest/DigestAuthTest already use. go-httpbin serves /get,
/redirect/n and /digest-auth the same way, so the test logic is
unchanged; the SSL variants disable certificate verification for the
self-signed test cert, as BaseAuthTest.SSL does.

RedirectTest.YouTube* is left pointing at youtube.com since it exercises
a real cross-host, http -> https redirect chain.

Claude-Session: https://claude.ai/code/session_0148ZAzsuYRYXkwcA7UFeh95
2026-09-11 16:35:11 -04:00
yhirose 3517f92e2f ci: remove the temporary windows-without-SSL flaky failure reporter
The intermittent failures it was tracking stopped after the graceful
drain before close in 8e702d3: no windows-without-SSL test failure on
master since 2026-08-09. Drop the reporting step, the issues: write
permission it needed, and the run_tests step id that only it used.

Claude-Session: https://claude.ai/code/session_0148ZAzsuYRYXkwcA7UFeh95
2026-09-11 16:16:25 -04:00
metsw24-maxandyhirose 0480ff77b8 reject ambiguously framed responses in client read paths (#2581)
* reject ambiguously framed responses in client read paths

* Accept non-chunked Transfer-Encoding responses in the client framing guard

RFC 9112 §6.3 treats requests and responses differently when the final
transfer coding is not chunked: a request's body length cannot be
determined and the server must answer 400, but a response's body simply
runs until the server closes the connection. read_content() and the
open_stream() body reader already do that, so such a response is not
ambiguous and rejecting it broke valid responses such as
"Transfer-Encoding: gzip" followed by a close.

Keep rejecting a Transfer-Encoding paired with a non-zero Content-Length,
which is the actual ambiguity, and drop the non-chunked clause from both
client read paths.

Tests: check that rejection surfaces as Error::Read, that a non-chunked
Transfer-Encoding response is read until close on both paths, and that
HEAD, 204 and 304 responses with both framing headers are not rejected.

Claude-Session: https://claude.ai/code/session_01JYPWKpbp4a881EdpEf2xSi

* Share the framing check and reuse existing test helpers

Factor "Transfer-Encoding with a non-zero Content-Length" into
detail::has_conflicting_content_length() next to
is_chunked_transfer_encoding(), and call it from the server request
guard and both client read paths so the rule and its RFC 9112 §6.3
rationale live in one place.

In the tests, drop the POSIX-only raw socket helper in favour of the
existing serve_single_response() and read_all(), which also lets the
tests run on Windows. Fold the stream-only test into the buffered one so
each case checks both Get() and open_stream(), and cover the HEAD/204/304
exclusion on the open_stream() path too.

Claude-Session: https://claude.ai/code/session_01JYPWKpbp4a881EdpEf2xSi

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-09-11 15:55:28 -04:00
KBSandyhirose 8d25b6a3ac Reject a Range first-byte-pos that overflows ssize_t (#2580)
* Reject a Range first-byte-pos that overflows ssize_t

parse_range_header initializes first to the -1 sentinel that means "no
first-byte-pos" and only overwrites it when detail::from_chars succeeds.
On std::errc::result_out_of_range the assignment is skipped and -1
survives, so "bytes=9223372036854775808-100" is parsed as the suffix
range "bytes=-100" and range_error serves the last 100 bytes instead of
returning 416.

Before the parser was rewritten onto detail::from_chars, std::stoll threw
std::out_of_range on the same input, the catch arm added in 8f8761e for
issue #705 returned false, and the request was answered with 416. The
catch arm is still there but from_chars reports through an error code, so
nothing reaches it any more.

get_header_value_u64 and parse_port already reject an out-of-range value
at their from_chars call sites; this was the remaining one that dropped
the error.

The last-byte-pos side is deliberately unchanged: -1 there is the
documented RFC 9110 14.1.2 "remainder of the representation" value, so an
oversized last-byte-pos stays accepted.

* Simplify the Range first-byte-pos overflow check

Parse the first-byte-pos straight into first, since a failed parse now
returns before first is read, and fold the overflow test into the
existing batch of rejected ranges. Also note on the last-byte-pos side
why an overflow there deliberately keeps -1.

Claude-Session: https://claude.ai/code/session_01JYPWKpbp4a881EdpEf2xSi

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-09-11 13:48:04 -04:00
metsw24-maxandyhirose 515b8f84af send each credential only to its own hop in write_request (#2579)
* send each credential only to its own hop in write_request

An SSLClient behind a proxy sent Proxy-Authorization inside the TLS tunnel, where the origin reads it, and sent the origin's Authorization on the CONNECT request the proxy reads. Attach each only on the message its hop actually reads.

* Keep default headers off the CONNECT request

set_default_headers() is typically used for origin credentials such as
Authorization, Cookie or API keys, but they were also attached to the
CONNECT request an SSLClient sends to its proxy, in plaintext before the
TLS tunnel exists. Default headers now go only on requests the origin
reads, the same split the previous commit makes for set_basic_auth and
set_bearer_token_auth.

Claude-Session: https://claude.ai/code/session_01JYPWKpbp4a881EdpEf2xSi

* Simplify per-hop credential handling and its tests

Flatten the Authorization insertion in write_request into one guard with
an else-if (Basic already took precedence over Bearer), and shorten the
comments around it. Fold DefaultHeadersStayOffConnect into the
CredentialsStayWithTheirHop helper, which now takes the list of headers
that must reach only the origin.

Claude-Session: https://claude.ai/code/session_01JYPWKpbp4a881EdpEf2xSi

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-09-11 13:25:48 -04:00
yhirose 88956ccad8 Self-host the httpbin auth-testing backend for BaseAuthTest/DigestAuthTest
These tests exercise the squid proxies by hitting /basic-auth and
/digest-auth on an external httpbin-style site. That site's identity has
already moved twice (httpbin.org -> httpcan.org, per #2300) chasing
uptime, and httpcan.org itself is now down (Cloudflare 502 from its
origin), failing CI with no code change involved.

Adds two containers to the existing squid docker-compose stack instead:
go-httpbin (mccutchen/go-httpbin) as the backend, and an nginx sidecar in
front of it under the single "httpbin" hostname so both the NoSSL tests
(port 80) and the SSL tests, which CONNECT-tunnel through the proxy to
port 443, resolve the same name -- go-httpbin only listens on one port at
a time, so it can't serve both protocols itself. nginx uses the repo's
existing self-signed test cert; the SSL client tests already disable
verification for it like other self-signed-cert tests in this suite.

go-httpbin was picked over the more feature-complete kennethreitz/httpbin
after finding the latter accepts a wrong digest-auth username as long as
the password matches -- confirmed with a direct curl against the
container, unrelated to anything in this repo. go-httpbin correctly
rejects both. The trade-off is losing SHA-512 digest-auth coverage here,
since go-httpbin only implements MD5 and SHA-256; nothing else in the
suite exercises SHA-512 digest auth against a live server. Response body
assertions are adjusted to go-httpbin's actual JSON shape (an added
"authorized" field, no "algorithm" field), and the domain changes from
httpcan.org to the self-hosted "httpbin".

This only affects 'make proxy'/'make proxy_mbedtls'/'make proxy_wolfssl'
and the Proxy Test CI workflow -- the default 'make' target is untouched.
2026-09-07 21:49:00 -04:00
yhirose f83d06538b Track Homebrew's clang-format version instead of a fixed pin
The previous commit pinned CI and the pre-commit hook to a fixed
clang-format 23.1.0, but the maintainer develops on macOS against
whatever version `brew` currently installs, which changes over time
as Homebrew updates the formula.

style-check now runs on macos-latest and installs clang-format via
`brew install`, so it tracks the same moving target the maintainer's
Mac does. The pre-commit hook switches from pre-commit's own pinned
mirror to a local hook that shells out to the system clang-format,
so a local commit and CI both go through the same Homebrew-installed
binary rather than two independently versioned copies.

Trade-off: this reintroduces the non-determinism a fixed pin avoids
-- a commit's style-check result can now change over time as Homebrew
updates the formula -- but that mirrors how the maintainer already
develops, which is the point.

Also install coreutils in CI: the style_check Makefile target needs
grealpath's --relative-to, which the macOS-native realpath lacks.
2026-09-07 20:15:31 -04:00
yhirose dc41dbd954 Pin style-check and pre-commit to clang-format 23.1.0
CI relied on ubuntu-latest's default apt clang-format (18.1.3), while the
pre-commit hook was pinned to a different 18.x build. Neither tracked a
specific, deliberately-chosen version, and the two could drift from each
other and from whatever a contributor has installed locally.

Both now pin the same clang-format 23.1.0 (latest stable), installed via
pipx in CI. Also scope the pre-commit hook's file matcher to the same set
of files test/Makefile's style_check target checks, since the previous
\.(cpp|cc|h)$ pattern reached into vendored code (test/gtest,
benchmark/crow) that must stay untouched.

Reformat httplib.h's brace-init spacing to match 23.1.0's output.
2026-09-07 17:18:45 -04:00
yhirose 6303a99ce1 Run clang-format on httplib.h and test.cc
Fixes formatting introduced in 199d7ee and d5f8858 that clang-format
18.1.3 (the version used by CI) disagrees with.
2026-09-07 16:29:08 -04:00
yhirose d5f8858731 Move ws::WebSocket's chrono set_read_timeout into the header half
Defined next to its non-template overload, it landed in the part of the header
that test_split compiles into httplib.cc, leaving a user TU's instantiation
with nothing to link against. The WebSocketClient overload of the same name has
always sat up with the class definitions; this one belongs there too.

Only test_split sees it -- a header-only build instantiates the template
wherever it is written, which is why the regular test target stayed green.
2026-09-03 15:00:02 -04:00
yhirose 199d7ee248 Tell a WebSocket read timeout apart from a closed connection
read() collapsed every failure into Fail and marked the connection closed with
it, so a read timeout could not be used to get control back and send on the
same connection -- it killed the connection instead. The information was
already there and thrown away: SocketStream::read records Error::Timeout, and
read_websocket_frame flattened it into a bool.

ReadResult gains Timeout, reported only when the timeout elapsed on a frame
boundary with nothing consumed, which is the only case where the stream can be
read again. Every multi-byte field now loops until it has its bytes, which also
fixes a frame header straddling the read buffer's boundary failing the frame:
Stream::read is allowed to return less than asked for, and only the payload
was reading in a loop.

ws::WebSocket::set_read_timeout() lets a server handler bound its own reads,
and WebSocketClient::set_read_timeout() now reaches an already-open connection
instead of only seeding the next connect().

The read timeout macro splits in two. A client waits forever by default -- a
read timeout is the caller's tool for taking back control, not a liveness
check, which is ping/pong's job -- while a server keeps the 300s that reclaims
a worker from a peer gone quiet. Defining the old name still sets both.

Also record a reason on the two WebSocketSSLStream::read failure paths that
returned -1 without one, so get_error() cannot report a previous call's
timeout, and make SocketStream's read timeout atomic now that it can be
changed while a read is in flight.
2026-09-03 14:32:13 -04:00
Avionic Harshit 9e2e33da56 let EXTRA_CXXFLAGS override -fsanitize=address (#2577) 2026-09-03 10:22:00 -04:00
Jhen-Jie Hongandyhirose 7d53a31d23 Don't compress a response whose handler already set Content-Encoding (#2575)
* Don't compress a response whose handler already set Content-Encoding

* Don't compress a pre-encoded response served from a file

The guard that stands down when a response already names a content coding
covered the responses that settle their coding in `apply_ranges()`, but a
file-backed one settles it in `static_file_encoding()`, which asked the
content-type overload and so never saw the field. With static file
compression enabled, a mount point naming the coding for a tree of
build-time compressed assets, and a handler setting the field on a
`set_file_content()` response, both had their stored bytes compressed a
second time and a second `Content-Encoding` field line appended.

A file-backed response has not been given a content type by the time its
coding is decided, which is the only reason it could not go through
`encoding_type()`. It takes the type as an argument now, so both paths share
the one guard instead of carrying a copy each.

`Response::content_encoding_` becomes `content_coding_`, after what it
holds. It names the coding chosen for the body, which is what its own
comment already called it, while the old name read as the value of the
`Content-Encoding` field whose presence is exactly what forces the coding to
`None`.

README gains the behaviour, including the part that stays with the handler:
`Vary` is added only to a coding the server chose, so a handler that picks a
representation from `Accept-Encoding` has to add the field itself.

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-08-31 20:44:12 -04:00
yhirose 9d6a7ee2c1 Release v0.54.1 2026-08-29 21:20:55 -04:00
yhirose 9ce15a14e5 Reject Digest challenges missing realm or nonce (RFC 7616 §3.3)
parse_www_authenticate() accepted any WWW-Authenticate: Digest
challenge that carried at least one auth-param, so a server sending
e.g. Digest qop="auth" with no realm/nonce would make it through.
make_digest_authentication_header() then dereferences auth.at("realm")
and auth.at("nonce") unconditionally, throwing std::out_of_range with
no try/catch on the retry path, which terminates the client process.

Now require both realm and nonce before treating a Digest challenge as
usable, same as if no Digest challenge were present at all.
2026-08-28 23:36:40 -04:00
96 changed files with 4495 additions and 1117 deletions

No files matched your search

+8 -31
View File
@@ -31,12 +31,19 @@ env:
jobs: jobs:
style-check: 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 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 continue-on-error: true
steps: steps:
- name: checkout - name: checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: install clang-format
run: |
brew update
brew install clang-format coreutils
- name: run style check - name: run style check
run: | run: |
clang-format --version clang-format --version
@@ -475,7 +482,6 @@ jobs:
runs-on: windows-latest runs-on: windows-latest
permissions: permissions:
contents: read contents: read
issues: write
if: > if: >
(github.event_name == 'push') || (github.event_name == 'push') ||
(github.event_name == 'pull_request' && (github.event_name == 'pull_request' &&
@@ -585,7 +591,6 @@ jobs:
- name: Build ${{ matrix.config.name }} - name: Build ${{ matrix.config.name }}
run: cmake --build build --config Release -- /v:m /clp:ShowCommandLine run: cmake --build build --config Release -- /v:m /clp:ShowCommandLine
- name: Run tests ${{ matrix.config.name }} - name: Run tests ${{ matrix.config.name }}
id: run_tests
if: ${{ matrix.config.run_tests }} if: ${{ matrix.config.run_tests }}
shell: pwsh shell: pwsh
working-directory: build/test working-directory: build/test
@@ -618,34 +623,6 @@ jobs:
} }
if ($failed) { exit 1 } if ($failed) { exit 1 }
Write-Host "All shards passed." 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: env:
VCPKG_ROOT: "C:/vcpkg" VCPKG_ROOT: "C:/vcpkg"
+9 -4
View File
@@ -1,7 +1,12 @@
repos: repos:
- repo: https://github.com/pre-commit/mirrors-clang-format - repo: local
rev: v18.1.8 # 最新バージョンを使用
hooks: hooks:
- id: clang-format - id: clang-format
files: \.(cpp|cc|h)$ name: clang-format
args: [-i] # インプレースで修正 # 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
View File
@@ -15,7 +15,7 @@
* HTTPLIB_REQUIRE_BROTLI (default off) * HTTPLIB_REQUIRE_BROTLI (default off)
* HTTPLIB_REQUIRE_ZSTD (default off) * HTTPLIB_REQUIRE_ZSTD (default off)
* HTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES (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_COMPILE (default off)
* HTTPLIB_INSTALL (default on) * HTTPLIB_INSTALL (default on)
* HTTPLIB_SHARED (default off) builds as a shared library (if HTTPLIB_COMPILE is 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) set(HTTPLIB_IS_USING_MACOSX_AUTOMATIC_ROOT_CERTIFICATES FALSE)
endif() endif()
set(HTTPLIB_IS_USING_NON_BLOCKING_GETADDRINFO ${HTTPLIB_USE_NON_BLOCKING_GETADDRINFO}) 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 # Threads needed for <thread> on some systems, and for <pthread.h> on Linux
set(THREADS_PREFER_PTHREAD_FLAG TRUE) 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 # 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>" "$<$<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 # 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. # 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::common>
$<$<BOOL:${HTTPLIB_IS_USING_BROTLI}>:Brotli::encoder> $<$<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_WOLFSSL}>:CPPHTTPLIB_WOLFSSL_SUPPORT>
$<$<BOOL:${HTTPLIB_IS_USING_MBEDTLS}>:CPPHTTPLIB_MBEDTLS_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> $<$<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 # CMake configuration files installation directory
+1 -1
View File
@@ -69,7 +69,7 @@ sse.on_error([](httplib::Error err) { });
#### Configuration #### Configuration
```cpp ```cpp
// Set reconnect interval (default: 3000ms) // Set reconnect interval (default: 3000ms, minimum: 100ms)
sse.set_reconnect_interval(5000); sse.set_reconnect_interval(5000);
// Set max reconnect attempts (default: 0 = unlimited) // Set max reconnect attempts (default: 0 = unlimited)
+16 -11
View File
@@ -4,7 +4,7 @@ This document describes the streaming extensions for cpp-httplib, providing an i
> **Important Notes**: > **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. > - **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. > - **Result is not thread-safe**: While `stream::Get()` can be called from multiple threads simultaneously, the returned `stream::Result` must be used from a single thread only.
@@ -114,7 +114,6 @@ The `httplib.h` header provides a more ergonomic iterator-style API.
#include "httplib.h" #include "httplib.h"
httplib::Client cli("http://localhost:8080"); httplib::Client cli("http://localhost:8080");
cli.set_follow_location(true);
... ...
// Simple GET // Simple GET
@@ -243,23 +242,29 @@ int main() {
```cpp ```cpp
#include "httplib.h" #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; httplib::Server svr;
svr.Get("/proxy/(.*)", [](const httplib::Request& req, httplib::Response& res) { svr.Get("/proxy/(.*)", [](const httplib::Request& req, httplib::Response& res) {
httplib::Client upstream("http://backend:8080"); auto upstream = std::make_shared<Upstream>();
auto handle = upstream.open_stream("/" + req.matches[1].str()); upstream->handle = upstream->cli.open_stream("GET", "/" + req.matches[1].str());
if (!handle.is_valid()) { if (!upstream->handle.is_valid()) {
res.status = 502; res.status = 502;
return; return;
} }
res.status = handle.response->status; res.status = upstream->handle.response->status;
res.set_chunked_content_provider( res.set_chunked_content_provider(
handle.response->get_header_value("Content-Type"), upstream->handle.response->get_header_value("Content-Type"),
[handle = std::move(handle)](size_t, httplib::DataSink& sink) mutable { [upstream](size_t, httplib::DataSink& sink) {
char buf[8192]; char buf[8192];
auto n = handle.read(buf, sizeof(buf)); auto n = upstream->handle.read(buf, sizeof(buf));
if (n > 0) { if (n > 0) {
sink.write(buf, static_cast<size_t>(n)); sink.write(buf, static_cast<size_t>(n));
return true; return true;
+39 -11
View File
@@ -57,14 +57,30 @@ if (ws.connect()) {
```cpp ```cpp
enum ReadResult : int { enum ReadResult : int {
Fail = 0, // Connection closed or error Fail = 0, // Connection closed or error
Text = 1, // UTF-8 text message Text = 1, // UTF-8 text message
Binary = 2, // Binary 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. 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 ### CloseStatus
```cpp ```cpp
@@ -103,7 +119,7 @@ using SubProtocolSelector =
std::function<std::string(const std::vector<std::string> &protocols)>; 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) ### WebSocket (Server-side)
@@ -135,9 +151,8 @@ bool is_open() const;
explicit WebSocketClient(const std::string &scheme_host_port_path, explicit WebSocketClient(const std::string &scheme_host_port_path,
const Headers &headers = {}); const Headers &headers = {});
// Constructor with a client certificate for mutual TLS (wss:// only, // Constructor with a client certificate for mutual TLS (wss:// only, SSL
// requires CPPHTTPLIB_OPENSSL_SUPPORT). The certificate is ignored for // builds only). The certificate is ignored for ws:// URLs.
// ws:// URLs.
struct PemMemory { struct PemMemory {
const char *cert_pem; const char *cert_pem;
size_t cert_pem_len; size_t cert_pem_len;
@@ -183,7 +198,7 @@ void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
template <class Rep, class Period> template <class Rep, class Period>
void set_connection_timeout(const std::chrono::duration<Rep, Period> &duration); void set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
// SSL configuration (wss:// only, requires CPPHTTPLIB_OPENSSL_SUPPORT) // SSL configuration (wss:// only, SSL builds only)
void set_ca_cert_path(const std::string &ca_cert_file_path, void set_ca_cert_path(const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path = std::string()); const std::string &ca_cert_dir_path = std::string());
void set_ca_cert_store(tls::ca_store_t store); void set_ca_cert_store(tls::ca_store_t store);
@@ -327,6 +342,18 @@ 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;
});
```
### Custom Headers and Timeouts ### Custom Headers and Timeouts
```cpp ```cpp
@@ -409,7 +436,8 @@ if (ws.connect()) {
| Macro | Default | Description | | Macro | Default | Description |
|---------------------------------------------|-------------------|----------------------------------------------------------| |---------------------------------------------|-------------------|----------------------------------------------------------|
| `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Maximum payload size per message | | `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_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_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_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 | | `CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS` | `0` (disabled) | Close the connection after N consecutive unacked pings |
@@ -444,9 +472,9 @@ ws.set_websocket_max_missed_pongs(2); // close after 2 consecutive unacked pings
The server side has the same `set_websocket_max_missed_pongs()`. 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 ## Threading Model
+92 -44
View File
@@ -33,7 +33,7 @@ Learn more in the [official documentation](https://yhirose.github.io/cpp-httplib
httplib::Server svr; httplib::Server svr;
// HTTPS // HTTPS
httplib::SSLServer svr; httplib::SSLServer svr("./cert.pem", "./key.pem");
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) { svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
res.set_content("Hello World!", "text/plain"); res.set_content("Hello World!", "text/plain");
@@ -71,7 +71,7 @@ cpp-httplib supports multiple TLS backends through an abstraction layer:
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` | | wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
> [!NOTE] > [!NOTE]
> **Mbed TLS / wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable. > **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
> [!NOTE] > [!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). > **BoringSSL (best-effort):** BoringSSL builds under `CPPHTTPLIB_OPENSSL_SUPPORT` and is exercised by CI against current upstream. Because BoringSSL does not guarantee API stability, support is best-effort — breakage may occasionally land. Two known behavioral differences vs OpenSSL: (1) BoringSSL's public headers require C++14 or later, so consumers must compile accordingly; (2) hostname verification is SAN-only per RFC 6125 §6.4.4 (no CN fallback).
@@ -86,7 +86,7 @@ httplib::SSLServer svr("./cert.pem", "./key.pem");
// Client // Client
httplib::Client cli("https://localhost:1234"); // scheme + host 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 httplib::SSLClient cli("localhost", 1234); // host, port
// Use your CA bundle // Use your CA bundle
@@ -103,8 +103,8 @@ cli.enable_server_hostname_verification(false);
When SSL operations fail, cpp-httplib provides detailed error information through `ssl_error()` and `ssl_backend_error()`: 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_error()` - Returns the TLS-level error as a backend-independent `httplib::tls::ErrorCode` value (e.g., `Fatal`, `CertVerifyFailed`), cast to `int`
- `ssl_backend_error()` - Returns the backend-specific error code (e.g., `ERR_get_error()` for OpenSSL/wolfSSL, return value for Mbed TLS) - `ssl_backend_error()` - Returns the backend-specific error code (e.g., `ERR_get_error()` for OpenSSL/wolfSSL, return value for Mbed TLS). With OpenSSL, a certificate verification failure reports the verify result (`X509_V_ERR_*`) here instead
```c++ ```c++
#define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT
@@ -230,7 +230,7 @@ cpp-httplib automatically integrates with the OS certificate store on macOS and
| Platform | Behavior | Disable (compile time) | | 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` | | 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, verification can also be disabled at runtime:
@@ -337,7 +337,7 @@ Note the following:
* The method name must be a valid HTTP method token (RFC 9110) and must be registered before `listen()` is called. * 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 the dedicated methods above instead.
* A rejected registration makes `is_valid()` return `false`, and `listen()` then fails rather than starting a server with a route that would never fire. * 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. * `Allow` and the WebDAV `DAV:` header are not generated automatically. Register an `Options` handler if clients need them.
### Bind a socket to multiple interfaces and any available port ### Bind a socket to multiple interfaces and any available port
@@ -347,6 +347,25 @@ int port = svr.bind_to_any_port("0.0.0.0");
svr.listen_after_bind(); 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 ### Static File Server
```cpp ```cpp
@@ -433,6 +452,9 @@ svr.set_logger([](const httplib::Request& req, const httplib::Response& res) {
}); });
``` ```
> [!NOTE]
> `req.path` is percent-decoded and may contain control characters such as CR/LF. Escape request data before writing it to a log file (see [docker/main.cc](docker/main.cc) for an example).
#### Pre-compression Logging #### Pre-compression Logging
You can also set a pre-compression logger to capture request/response data before compression is applied: You can also set a pre-compression logger to capture request/response data before compression is applied:
@@ -496,7 +518,7 @@ svr.set_exception_handler([](const auto& req, auto& res, std::exception_ptr ep)
``` ```
> [!CAUTION] > [!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 ### Pre routing handler
@@ -545,22 +567,23 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
``` ```
Request received 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") ├─ 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)
│ │
├─ route matching → req.matched_route is set ├─ route matching → req.matched_route is set
│ │
├─ pre_request_handler route matched, body NOT read yet ├─ 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 ├─ 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 a thrown exception → exception_handler
On an error status (4xx/5xx) → error_handler On an error status (4xx/5xx) → error_handler
@@ -568,6 +591,10 @@ Request received
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.
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 ### Response user data
`res.user_data` is a type-safe key-value store that lets pre-routing or pre-request handlers pass arbitrary data to route handlers. `res.user_data` is a type-safe key-value store that lets pre-routing or pre-request handlers pass arbitrary data to route handlers.
@@ -584,7 +611,7 @@ svr.set_pre_routing_handler([](const auto& req, auto& res) {
return Server::HandlerResponse::Unhandled; 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"); auto* ctx = res.user_data.get<AuthContext>("auth");
if (!ctx) { if (!ctx) {
res.status = StatusCode::Unauthorized_401; res.status = StatusCode::Unauthorized_401;
@@ -827,7 +854,9 @@ svr.Get("/content", [&](const Request &req, Response &res) {
### 'Expect: 100-continue' handler ### '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 ```cpp
// Send a '417 Expectation Failed' response. // Send a '417 Expectation Failed' response.
@@ -879,7 +908,7 @@ Please see [Server example](https://github.com/yhirose/cpp-httplib/blob/master/e
`ThreadPool` is used as the **default** task queue, with dynamic scaling support. By default, it maintains a base thread count of 8 or `std::thread::hardware_concurrency() - 1` (whichever is greater), and can scale up to 4x that count under load. You can change these with `CPPHTTPLIB_THREAD_POOL_COUNT` and `CPPHTTPLIB_THREAD_POOL_MAX_COUNT`. `ThreadPool` is used as the **default** task queue, with dynamic scaling support. By default, it maintains a base thread count of 8 or `std::thread::hardware_concurrency() - 1` (whichever is greater), and can scale up to 4x that count under load. You can change these with `CPPHTTPLIB_THREAD_POOL_COUNT` and `CPPHTTPLIB_THREAD_POOL_MAX_COUNT`.
When all threads are busy and a new task arrives, a temporary thread is spawned (up to the maximum). When a dynamic thread finishes its task and the queue is empty, or after an idle timeout, it exits automatically. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`. When all threads are busy and a new task arrives, a temporary thread is spawned (up to the maximum). A dynamic thread exits automatically once it has waited for the idle timeout without receiving a task. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`.
If you want to set the thread counts at runtime: If you want to set the thread counts at runtime:
@@ -1013,6 +1042,8 @@ enum class Error {
HTTPParsing, HTTPParsing,
InvalidRangeHeader, InvalidRangeHeader,
UnsupportedContentEncoding, UnsupportedContentEncoding,
WebSocketHandshake,
UserCallbackException,
}; };
``` ```
@@ -1228,7 +1259,7 @@ std::string body = ...;
auto res = cli.Post( auto res = cli.Post(
"/stream", body.size(), "/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); sink.write(body.data() + offset, length);
return true; // return 'false' if you want to cancel the request. return true; // return 'false' if you want to cancel the request.
}, },
@@ -1281,7 +1312,7 @@ cli.set_bearer_token_auth("token");
``` ```
> [!NOTE] > [!NOTE]
> OpenSSL is required for Digest Authentication. > A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
### Proxy server support ### Proxy server support
@@ -1299,12 +1330,12 @@ cli.set_proxy_bearer_token_auth("pass");
``` ```
> [!NOTE] > [!NOTE]
> OpenSSL is required for Digest Authentication. > A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
#### Bypass the proxy for specific hosts (`NO_PROXY`) #### Bypass the proxy for specific hosts (`NO_PROXY`)
```cpp ```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. Each pattern is `*`, a hostname suffix, an IP literal, or a CIDR block.
@@ -1449,8 +1480,8 @@ for (auto it = req.headers.equal_range("Accept-Encoding").first;
std::cout << it->second << std::endl; std::cout << it->second << std::endl;
} }
// get_header_value(key, id) reaches a specific one directly. // get_header_value(key, def, id) reaches a specific one directly.
auto second = req.get_header_value("Accept-Encoding", 1); // "br" 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. `Headers` matches field names case-insensitively, as before. `Params`, `FormFields`, and `FormFiles` are case-sensitive.
@@ -1460,7 +1491,7 @@ auto second = req.get_header_value("Accept-Encoding", 1); // "br"
## Payload Limit ## Payload Limit
The maximum payload body size is limited to 100MB by default for both server and client. You can change it with `set_payload_max_length()` or by defining `CPPHTTPLIB_PAYLOAD_MAX_LENGTH` at compile time. Setting it to `0` disables the limit entirely. The maximum payload body size is limited to 100MB by default for both server and client. You can change it with `set_payload_max_length()` or by defining `CPPHTTPLIB_PAYLOAD_MAX_LENGTH` at compile time. Setting it to `0` disables the limit entirely. On the client, a request made with a content receiver is not limited unless you call `set_payload_max_length()` yourself, so that a large download can be streamed without raising the limit first.
## Compression ## Compression
@@ -1469,10 +1500,28 @@ The server can apply compression to the following MIME type contents:
- all text types except text/event-stream - all text types except text/event-stream
- image/svg+xml - image/svg+xml
- application/javascript - application/javascript
- application/x-javascript
- application/json - application/json
- application/ld+json
- application/xml - application/xml
- application/protobuf
- application/xhtml+xml - 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 ### Static file compression
@@ -1596,7 +1645,6 @@ Process large responses without loading everything into memory.
```c++ ```c++
httplib::Client cli("localhost", 8080); httplib::Client cli("localhost", 8080);
cli.set_follow_location(true);
... ...
auto result = httplib::stream::Get(cli, "/large-file"); auto result = httplib::stream::Get(cli, "/large-file");
@@ -1676,7 +1724,7 @@ SSL is also supported via `wss://` scheme (e.g. `WebSocketClient("wss://example.
> **WebSocket extensions are not supported.** `permessage-deflate` and other RFC 6455 extensions are not implemented. If a client proposes them via `Sec-WebSocket-Extensions`, the server silently declines them in its handshake response. > **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. See [README-websocket.md](README-websocket.md) for more details.
@@ -1685,12 +1733,14 @@ See [README-websocket.md](README-websocket.md) for more details.
`set_socket_opt` is a convenience wrapper around `setsockopt` for setting integer socket options: `set_socket_opt` is a convenience wrapper around `setsockopt` for setting integer socket options:
```cpp ```cpp
auto sock = svr.socket(); svr.set_socket_options([](socket_t sock) {
httplib::set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); httplib::default_socket_options(sock);
httplib::set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
});
``` ```
> [!TIP] > [!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 ## Split httplib.h into .h and .cc
@@ -1719,7 +1769,9 @@ Dockerfile for static HTTP server is available. Port number of this HTTP server
... ...
> docker run --rm -it -p 8080:80 -v ./docker/html:/html cpp-httplib-server > 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: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 / 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 ..." 192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
@@ -1729,7 +1781,9 @@ From Docker Hub
```bash ```bash
> docker run --rm -it -p 8080:80 -v ./docker/html:/html yhirose4dockerhub/cpp-httplib-server > 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: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 / 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 ..." 192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
@@ -1741,19 +1795,13 @@ NOTE
### Regular Expression Stack Overflow ### Regular Expression Stack Overflow
> [!CAUTION] > [!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 > ```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("/users/:id", handler); // Path parameters
> svr.Get(R"(/api/v\d+/.*)", handler); // More specific patterns > svr.Get(R"(/api/v\d+/.*)", handler); // Regex route, limited to short paths
> ``` > ```
### g++ ### g++
+29 -7
View File
@@ -48,6 +48,23 @@ std::string get_error_time_format() {
return ss.str(); 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: // NGINX Combined log format:
// $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent // $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent
// "$http_referer" "$http_user_agent" // "$http_referer" "$http_user_agent"
@@ -55,18 +72,22 @@ void nginx_access_logger(const Request &req, const Response &res) {
std::string remote_user = std::string remote_user =
"-"; // cpp-httplib doesn't have built-in auth user tracking "-"; // cpp-httplib doesn't have built-in auth user tracking
auto time_local = get_time_format(); 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 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"); auto http_referer = req.get_header_value("Referer");
if (http_referer.empty()) http_referer = "-"; if (http_referer.empty()) http_referer = "-";
auto http_user_agent = req.get_header_value("User-Agent"); auto http_user_agent = req.get_header_value("User-Agent");
if (http_user_agent.empty()) http_user_agent = "-"; if (http_user_agent.empty()) http_user_agent = "-";
std::cout << std::format("{} - {} [{}] \"{}\" {} {} \"{}\" \"{}\"", std::cout << std::format("{} - {} [{}] \"{}\" {} {} \"{}\" \"{}\"",
req.remote_addr, remote_user, time_local, request, req.remote_addr, remote_user, time_local,
status, body_bytes_sent, http_referer, escape_log(request), status, body_bytes_sent,
http_user_agent) escape_log(http_referer), escape_log(http_user_agent))
<< std::endl; << std::endl;
} }
@@ -79,14 +100,15 @@ void nginx_error_logger(const Error &err, const Request *req) {
if (req) { if (req) {
auto request = 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"); auto host = req->get_header_value("Host");
if (host.empty()) host = "-"; if (host.empty()) host = "-";
std::cerr << std::format("{} [{}] {}, client: {}, request: " std::cerr << std::format("{} [{}] {}, client: {}, request: "
"\"{}\", host: \"{}\"", "\"{}\", host: \"{}\"",
time_local, level, to_string(err), time_local, level, to_string(err),
req->remote_addr, request, host) req->remote_addr, escape_log(request),
escape_log(host))
<< std::endl; << std::endl;
} else { } else {
// If no request context, just log the error // If no request context, just log the error
+1 -1
View File
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
[site] [site]
title = "cpp-httplib" title = "cpp-httplib"
version = "0.54.0" version = "0.61.0"
hostname = "https://yhirose.github.io" hostname = "https://yhirose.github.io"
base_path = "/cpp-httplib" base_path = "/cpp-httplib"
footer_message = "© 2026 Yuji Hirose. All rights reserved." footer_message = "© 2026 Yuji Hirose. All rights reserved."
+1 -1
View File
@@ -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()`. 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 ## Receive a JSON response
@@ -21,7 +21,7 @@ auto res = cli.Get("/large-file",
std::cout << std::endl; 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 ## 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. > **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). > For a concrete example of saving to a file, see [C01. Get the response body / save to a file](../c01-get-response-body).
@@ -16,7 +16,7 @@ cli.set_max_timeout(5000); // 5 seconds (in milliseconds)
auto res = cli.Get("/slow-endpoint"); 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` ## Use `std::chrono`
+9 -8
View File
@@ -4,30 +4,29 @@ order: 14
status: "draft" 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 ```cpp
httplib::Client cli("https://api.example.com"); httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
auto res1 = cli.Get("/users/1"); auto res1 = cli.Get("/users/1");
auto res2 = cli.Get("/users/2"); // reuses the same connection auto res2 = cli.Get("/users/2"); // reuses the same connection
auto res3 = cli.Get("/users/3"); // 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 ```cpp
cli.set_keep_alive(false); cli.set_keep_alive(false);
``` ```
For normal use, leave it on (the default).
## Don't create a `Client` per request ## 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. 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 // Bad: a new connection every iteration
for (auto id : ids) { for (auto id : ids) {
httplib::Client cli("https://api.example.com"); httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
cli.Get("/users/" + id); cli.Get("/users/" + id);
} }
// Good: the connection is reused // Good: the connection is reused
httplib::Client cli("https://api.example.com"); httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
for (auto id : ids) { for (auto id : ids) {
cli.Get("/users/" + id); 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. 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" 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 ## Build-time setup
@@ -13,10 +13,11 @@ To use compression, define these macros before including `httplib.h`:
```cpp ```cpp
#define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate #define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate
#define CPPHTTPLIB_BROTLI_SUPPORT // brotli #define CPPHTTPLIB_BROTLI_SUPPORT // brotli
#define CPPHTTPLIB_ZSTD_SUPPORT // zstd
#include <httplib.h> #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 ## Compress the request body
@@ -28,7 +29,7 @@ std::string big_payload = build_payload();
auto res = cli.Post("/api/data", big_payload, "application/json"); auto res = cli.Post("/api/data", big_payload, "application/json");
``` ```
With `set_compress(true)`, the body of POST or PUT requests gets gzipped before sending. The server needs to handle compressed bodies too. With `set_compress(true)`, the body of POST or PUT requests is compressed before sending. The encoding is the first one enabled in your build, in the order Brotli, gzip, Zstd. The server needs to handle compressed bodies too.
## Decompress the response ## 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. 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.
+1 -1
View File
@@ -55,7 +55,7 @@ You often want internal endpoints to skip the proxy. Configure a bypass list wit
```cpp ```cpp
cli.set_proxy("proxy.internal", 8080); 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: Each entry is one of:
@@ -29,8 +29,8 @@ Use `if (res)` to check success. On failure, `res.error()` returns a `httplib::E
| --- | --- | | --- | --- |
| `Error::Connection` | Couldn't connect to the server | | `Error::Connection` | Couldn't connect to the server |
| `Error::ConnectionTimeout` | Connection timeout (`set_connection_timeout`) | | `Error::ConnectionTimeout` | Connection timeout (`set_connection_timeout`) |
| `Error::Read` / `Error::Write` | Error during send or receive | | `Error::Read` / `Error::Write` | Error during send or receive. A timeout from `set_read_timeout` or `set_max_timeout` is also reported as `Error::Read` |
| `Error::Timeout` | Overall timeout set via `set_max_timeout` | | `Error::Timeout` | A body read timed out in `stream::Get()` or `SSEClient` |
| `Error::ExceedRedirectCount` | Too many redirects | | `Error::ExceedRedirectCount` | Too many redirects |
| `Error::SSLConnection` | TLS handshake failed | | `Error::SSLConnection` | TLS handshake failed |
| `Error::SSLServerVerification` | Server certificate verification failed | | `Error::SSLServerVerification` | Server certificate verification failed |
+8 -3
View File
@@ -24,19 +24,24 @@ if (!res) {
} }
``` ```
`ssl_error()` returns the error code from the SSL library (e.g., OpenSSL's `SSL_get_error()`). `ssl_backend_error()` gives you the backend's more detailed error value — for OpenSSL, that's `ERR_get_error()`. `ssl_error()` is a backend-independent TLS error category: an `httplib::tls::ErrorCode` cast to `int`. `ssl_backend_error()` gives you the backend's own error value. With OpenSSL that is `ERR_get_error()` when the handshake failed, and the verify result (`X509_V_ERR_*`) when certificate verification failed.
## Format OpenSSL errors as strings ## 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 ```cpp
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/x509.h>
if (res.ssl_backend_error() != 0) { if (res.error() == httplib::Error::SSLConnection) {
char buf[256]; char buf[256];
ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf)); ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf));
std::cerr << "openssl: " << buf << std::endl; 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;
} }
``` ```
+2 -2
View File
@@ -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 ## Connection lifecycle and errors
@@ -55,7 +55,7 @@ sse.on_error([](httplib::Error err) {
}); });
``` ```
Hook into connection open and error events. Even when the error handler fires, `SSEClient` keeps trying to reconnect in the background. Hook into connection open and error events. Even when the error handler fires, `SSEClient` keeps trying to reconnect in the background. The exceptions are a 204, 403, or 404 response, after which it stops.
## Run asynchronously ## Run asynchronously
@@ -30,7 +30,7 @@ You can even mount multiple directories at the same path — they're searched in
## Combine with API handlers ## 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 ```cpp
svr.Get("/api/users", [](const auto &req, auto &res) { 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( res.set_content_provider(
total_size, "application/octet-stream", total_size, "application/octet-stream",
[](size_t offset, size_t length, httplib::DataSink &sink) { [](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()); sink.write(data.data(), data.size());
return true; 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 ## Just send a file
@@ -96,7 +96,7 @@ svr.Post("/upload",
}); });
``` ```
When `content_reader` returns `false`, set the response status yourself. The rest of the body is left unread and the connection is closed, so a client that is still sending sees the connection drop. When `content_reader` returns `false`, the response status becomes 400 (413 if the body exceeded the size limit). Set it yourself if you want a different one. The rest of the body is left unread and the connection is closed, so a client that is still sending sees the connection drop.
> **Warning:** When you use `HandlerWithContentReader`, `req.body` stays **empty**. Handle the body yourself inside the callbacks. > **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 ## 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 ## Streaming responses are compressed too
@@ -37,6 +37,8 @@ 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. `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.
## Return values ## Return values
Same as pre-routing — return `HandlerResponse`. Same as pre-routing — return `HandlerResponse`.
+1 -1
View File
@@ -37,7 +37,7 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
## Typical value types ## Typical value types
Strings, numbers, structs, `std::shared_ptr` — anything copyable or movable works. Strings, numbers, structs, `std::shared_ptr`: anything copyable works.
```cpp ```cpp
res.user_data.set("user_id", std::string{"42"}); res.user_data.set("user_id", std::string{"42"});
@@ -48,7 +48,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled; 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 *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
auto elapsed = start auto elapsed = start
? std::chrono::duration_cast<std::chrono::milliseconds>( ? std::chrono::duration_cast<std::chrono::milliseconds>(
@@ -43,15 +43,40 @@ svr.listen_after_bind();
## Check the return values ## 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 ```cpp
if (!svr.bind_to_port("0.0.0.0", 8080)) { 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; return 1;
} }
``` ```
`listen_after_bind()` blocks until the server stops and returns `true` on a clean shutdown. `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()`. > **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,6 @@ int main() {
## What happens to in-flight requests ## 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. > **Warning:** There's a wait between calling `stop()` and `listen()` returning — it's the time in-flight requests take to finish. To enforce a timeout, you'll need to add your own shutdown timer in application code.
@@ -19,7 +19,7 @@ svr.Get("/", [](const auto &, auto &res) {
svr.listen("/tmp/httplib.sock", 80); 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 ## Client side
+1 -1
View File
@@ -55,7 +55,7 @@ httplib::SSLClient cli("api.example.com", 443,
auto res = cli.Get("/"); 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. The client side has the same `PemMemory` struct too, letting you set the client certificate from PEM in memory.
@@ -36,6 +36,7 @@ The `read()` return value is a `ReadResult` enum:
- `ReadResult::Text`: received a text message - `ReadResult::Text`: received a text message
- `ReadResult::Binary`: received a binary message - `ReadResult::Binary`: received a binary message
- `ReadResult::Fail`: error, or connection closed - `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 ## Client: talk to the echo server
@@ -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()`. 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. 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. `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). > For handling a closed connection, see [W03. Handle connection close](../w03-websocket-close).
@@ -42,6 +42,9 @@ switch (result) {
case httplib::ws::ReadResult::Fail: case httplib::ws::ReadResult::Fail:
// error or closed // error or closed
break; break;
case httplib::ws::ReadResult::Timeout:
// read timeout elapsed; the connection is still open
break;
} }
``` ```
@@ -9,7 +9,7 @@ status: "draft"
| Kind | API | Default | | Kind | API | Default |
| --- | --- | --- | | --- | --- | --- |
| Connection | `set_connection_timeout` | 300s | | 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 | | Write | `set_write_timeout` | 5s |
## Basic usage ## 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` ## Use `std::chrono`
@@ -40,9 +40,44 @@ ws.set_read_timeout(30s);
ws.set_write_timeout(10s); 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. > Unresponsive-peer detection via Ping/Pong is a separate mechanism. See [W02. Set a WebSocket Heartbeat](../w02-websocket-ping) for details.
+1 -9
View File
@@ -18,10 +18,6 @@ Simply pass the path to a model file to `llamalib::Llama`, and model loading, co
int main() { int main() {
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"}; 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 ... // ... 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 ## 2.3 Complete Code
@@ -111,10 +107,6 @@ int main() {
// Load the model downloaded in Chapter 1 // Load the model downloaded in Chapter 1
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"}; 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 // Log requests and responses
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status 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 - 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 - 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 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 - `data: [DONE]` follows the OpenAI API convention to signal the end of the stream to the client
## 3.4 Complete Code ## 3.4 Complete Code
@@ -107,10 +107,6 @@ int main() {
// Load the GGUF model // Load the GGUF model
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"}; 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 // Log requests and responses
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
@@ -219,7 +219,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); cli.set_follow_location(true);
cli.set_read_timeout(std::chrono::hours(1));
auto url = "/" + model.repo + "/resolve/main/" + model.filename; auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / 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) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging Face redirects to a CDN 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 url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename; auto path = get_models_dir() / model.filename;
@@ -539,10 +537,6 @@ int main() {
auto llm = llamalib::Llama{path}; auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // Protect access during model switching 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) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl; << std::endl;
-5
View File
@@ -939,7 +939,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging Face redirects to CDN cli.set_follow_location(true); // Hugging Face redirects to CDN
cli.set_read_timeout(std::chrono::hours(1)); // Long timeout for large models
auto url = "/" + model.repo + "/resolve/main/" + model.filename; auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename; auto path = get_models_dir() / model.filename;
@@ -1008,10 +1007,6 @@ int main() {
} }
auto llm = llamalib::Llama{path}; auto llm = llamalib::Llama{path};
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl; << std::endl;
@@ -407,7 +407,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging Face redirects to a CDN 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 url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename; auto path = get_models_dir() / model.filename;
@@ -469,10 +468,6 @@ int main() {
auto llm = llamalib::Llama{path}; auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // Protect access during model switching 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) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl; << std::endl;
+10 -6
View File
@@ -11,13 +11,17 @@ Over the course of six chapters, we built a translation desktop app from scratch
## 7.1 Source Code Location ## 7.1 Source Code Location
```ascii ```ascii
llama.cpp/tools/server/ llama.cpp/
├── server.cpp # Main server implementation ├── tools/server/
├── httplib.h # cpp-httplib (bundled version) │ ├── 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 ## 7.2 OpenAI-Compatible API
@@ -141,7 +145,7 @@ Let's organize the differences we've covered.
| SSE format | Tokens only | OpenAI-compatible JSON | | SSE format | Tokens only | OpenAI-compatible JSON |
| KV cache | Cleared each time | Prefix reuse | | KV cache | Cleared each time | Prefix reuse |
| Structured output | None | JSON Schema / grammar constraints | | 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. 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.
+2 -2
View File
@@ -200,8 +200,8 @@ auto res = cli.Post("/submit", httplib::Params{
}); });
if (res) { if (res) {
std::cout << res->body << std::endl; std::cout << res->body << std::endl;
// age = 30
// name = Alice // name = Alice
// age = 30
} }
``` ```
@@ -241,7 +241,7 @@ auto res = cli.Get("/hi");
if (!res) { if (!res) {
// Connection error // Connection error
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl; std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
// Error: Connection // Error: Could not establish connection
return 1; return 1;
} }
@@ -95,7 +95,7 @@ svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080); 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 ## Adding response headers
+2
View File
@@ -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 ## Using WSS
WebSocket over HTTPS (WSS) is also supported. On the server side, just register a WebSocket handler on `httplib::SSLServer`. WebSocket over HTTPS (WSS) is also supported. On the server side, just register a WebSocket handler on `httplib::SSLServer`.
+4 -4
View File
@@ -50,7 +50,7 @@ svr.Get("/stream", [](const auto &, auto &res) {
res.set_chunked_content_provider("text/plain", res.set_chunked_content_provider("text/plain",
[](size_t offset, httplib::DataSink &sink) { [](size_t offset, httplib::DataSink &sink) {
sink.write("chunk\n", 6); sink.write("chunk\n", 6);
return true; // Return false to finish return true; // Call sink.done() to finish
}); });
}); });
``` ```
@@ -155,7 +155,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
}); });
svr.set_post_routing_handler([](const auto &req, auto &res) { 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"); res.set_header("X-Server", "cpp-httplib");
}); });
``` ```
@@ -168,7 +168,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled; 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"); auto *user = res.user_data.get<std::string>("auth_user");
res.set_content("Hello, " + *user, "text/plain"); res.set_content("Hello, " + *user, "text/plain");
}); });
@@ -205,7 +205,7 @@ In addition to TCP, we support Unix Domain Sockets. You can use them for inter-p
// Server // Server
httplib::Server svr; httplib::Server svr;
svr.set_address_family(AF_UNIX); 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 ```cpp
+1 -1
View File
@@ -17,7 +17,7 @@ auto res = cli.Post("/api/users", j.dump(), "application/json");
`Post()`の第2引数にJSON文字列、第3引数にContent-Typeを渡します。`Put()`や`Patch()`でも同じ形です。 `Post()`の第2引数にJSON文字列、第3引数にContent-Typeを渡します。`Put()`や`Patch()`でも同じ形です。
> **Warning:** 第3引数のContent-Typeを省略すると、サーバー側でJSONとして認識されないことがあります。`"application/json"`を必ず指定しましょう。 > **Warning:** 第3引数のContent-Typeが`"application/json"`でないと、サーバー側でJSONとして扱われないことがあります。忘れずに指定しましょう。
## JSONレスポンスを受け取る ## JSONレスポンスを受け取る
@@ -21,7 +21,7 @@ auto res = cli.Get("/large-file",
std::cout << std::endl; 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`と進捗コールバックは同時に使えます。ファイルに書き出しながら進捗を表示したいときは、両方を渡しましょう。 > **Note:** `ContentReceiver`と進捗コールバックは同時に使えます。ファイルに書き出しながら進捗を表示したいときは、両方を渡しましょう。
> ファイル保存と組み合わせる具体例は[C01. レスポンスボディを取得する / ファイルに保存する](../c01-get-response-body)も参照してください。 > ファイル保存と組み合わせる具体例は[C01. レスポンスボディを取得する / ファイルに保存する](../c01-get-response-body)も参照してください。
@@ -16,11 +16,11 @@ cli.set_max_timeout(5000); // 5秒(ミリ秒単位)
auto res = cli.Get("/slow-endpoint"); auto res = cli.Get("/slow-endpoint");
``` ```
ミリ秒単位で指定します。接続、送信、受信をすべて含めて、リクエスト全体が指定時間を超えたら打ち切られます。 ミリ秒単位で指定します。リクエストを始めてからこの時間が過ぎると、レスポンスを待っている途中でも打ち切られます。ただし、接続や送信で待たされる時間まで短くなるわけではありません。そちらは`set_connection_timeout`と`set_write_timeout`で調整します。
## `std::chrono`で指定する ## `std::chrono`で指定する
こちらも`std::chrono`の期間を受け取るオーバーロードがあります。 こちらにも、`std::chrono`の期間を受け取るオーバーロードがあります。
```cpp ```cpp
using namespace std::chrono_literals; using namespace std::chrono_literals;
+10 -9
View File
@@ -4,43 +4,44 @@ order: 14
status: "draft" 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 ```cpp
httplib::Client cli("https://api.example.com"); httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
auto res1 = cli.Get("/users/1"); auto res1 = cli.Get("/users/1");
auto res2 = cli.Get("/users/2"); // 同じ接続を再利用 auto res2 = cli.Get("/users/2"); // 同じ接続を再利用
auto res3 = cli.Get("/users/3"); // 同じ接続を再利用 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 ```cpp
cli.set_keep_alive(false); cli.set_keep_alive(false);
``` ```
ただし、普段はオン(デフォルト)のままで問題ありません。
## リクエストごとに`Client`を作らない ## リクエストごとに`Client`を作らない
1回のリクエストのたびに`Client`をスコープから抜けて破棄すると、接続の再利用は効きません。ループの外でインスタンスを作り、中で使い回しましょう。 リクエストのたびに`Client`を作っては破棄していると、接続は再利用されません。インスタンスはループの外で作り、中で使い回しましょう。
```cpp ```cpp
// NG: 毎回接続が切れる // NG: 毎回接続が切れる
for (auto id : ids) { for (auto id : ids) {
httplib::Client cli("https://api.example.com"); httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
cli.Get("/users/" + id); cli.Get("/users/" + id);
} }
// OK: 接続が再利用される // OK: 接続が再利用される
httplib::Client cli("https://api.example.com"); httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
for (auto id : ids) { for (auto id : ids) {
cli.Get("/users/" + id); cli.Get("/users/" + id);
} }
@@ -50,4 +51,4 @@ for (auto id : ids) {
複数のスレッドから並行にリクエストを送りたいときは、スレッドごとに別々の`Client`インスタンスを持つのが無難です。1つの`Client`は1本のTCP接続を使い回すので、同じインスタンスに複数スレッドから同時にリクエストを投げると、結局どこかで直列化されます。 複数のスレッドから並行にリクエストを送りたいときは、スレッドごとに別々の`Client`インスタンスを持つのが無難です。1つの`Client`は1本のTCP接続を使い回すので、同じインスタンスに複数スレッドから同時にリクエストを投げると、結局どこかで直列化されます。
> **Note:** サーバー側のKeep-Aliveタイムアウトを超えると、サーバーが接続を切ります。その場合cpp-httplibは自動で再接続して再試行するので、アプリケーションコードで気にする必要はありません。 > **Note:** サーバー側のKeep-Aliveタイムアウトを超えると、サーバーが接続を切ります。cpp-httplibは次のリクエストを送る前にそれに気付いて接続し直すので、アプリケーション側で気にする必要はありません。
@@ -4,7 +4,7 @@ order: 15
status: "draft" status: "draft"
--- ---
cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlibまたはBrotliを有効にしてビルドしておく必要があります。 cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlib、Brotli、Zstdのいずれかを有効にしてビルドしておく必要があります。
## ビルド時の準備 ## ビルド時の準備
@@ -13,10 +13,11 @@ cpp-httplibは送信時の圧縮と受信時の解凍をサポートしていま
```cpp ```cpp
#define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate #define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate
#define CPPHTTPLIB_BROTLI_SUPPORT // brotli #define CPPHTTPLIB_BROTLI_SUPPORT // brotli
#define CPPHTTPLIB_ZSTD_SUPPORT // zstd
#include <httplib.h> #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"); auto res = cli.Post("/api/data", big_payload, "application/json");
``` ```
`set_compress(true)`を呼んでおくと、POSTやPUTのリクエストボディがgzipで圧縮されて送信されます。サーバー側が対応している必要があります。 `set_compress(true)`を呼んでおくと、POSTやPUTのリクエストボディが圧縮されて送信されます。圧縮方式は、ビルドで有効にしたもののうち、Brotli、gzip、Zstdの順で最初に当てはまるものです。サーバー側もその方式に対応している必要があります。
## レスポンスを解凍する ## レスポンスを解凍する
@@ -44,4 +45,4 @@ std::cout << res->body << std::endl;
デフォルトで有効なので、通常は何もしなくても解凍されます。あえて生の圧縮データを触りたいときだけ`set_decompress(false)`にしましょう。 デフォルトで有効なので、通常は何もしなくても解凍されます。あえて生の圧縮データを触りたいときだけ`set_decompress(false)`にしましょう。
> **Warning:** `CPPHTTPLIB_ZLIB_SUPPORT`を定義せずにビルドすると、`set_compress()`や`set_decompress()`を呼んでも何も起こりません。マクロの定義を忘れていないか、最初に確認しましょう。 > **Warning:** 圧縮ライブラリを1つも有効にしていないビルドでは、`set_compress(true)`を呼んでもリクエストは圧縮されません。また、ビルドで有効にしていない方式で圧縮されたレスポンスが返ってくると、リクエストは`Error::UnsupportedContentEncoding`で失敗します。うまく動かないときは、まずマクロの定義を確認しましょう。
+1 -1
View File
@@ -55,7 +55,7 @@ cli.set_bearer_token_auth("api-token"); // エンドサーバー向け
```cpp ```cpp
cli.set_proxy("proxy.internal", 8080); cli.set_proxy("proxy.internal", 8080);
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"}); cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
``` ```
エントリは次のいずれかです。 エントリは次のいずれかです。
@@ -29,8 +29,8 @@ if (res) {
| --- | --- | | --- | --- |
| `Error::Connection` | サーバーに接続できなかった | | `Error::Connection` | サーバーに接続できなかった |
| `Error::ConnectionTimeout` | 接続タイムアウト(`set_connection_timeout`) | | `Error::ConnectionTimeout` | 接続タイムアウト(`set_connection_timeout`) |
| `Error::Read` / `Error::Write` | 送受信中のエラー | | `Error::Read` / `Error::Write` | 送受信中のエラー。`set_read_timeout`や`set_max_timeout`によるタイムアウトも`Error::Read`になる |
| `Error::Timeout` | `set_max_timeout`で設定した全体タイムアウト | | `Error::Timeout` | `stream::Get()`や`SSEClient`で、ボディの読み取りがタイムアウトした |
| `Error::ExceedRedirectCount` | リダイレクト回数が上限を超えた | | `Error::ExceedRedirectCount` | リダイレクト回数が上限を超えた |
| `Error::SSLConnection` | TLSハンドシェイクに失敗 | | `Error::SSLConnection` | TLSハンドシェイクに失敗 |
| `Error::SSLServerVerification` | サーバー証明書の検証に失敗 | | `Error::SSLServerVerification` | サーバー証明書の検証に失敗 |
@@ -38,7 +38,7 @@ if (res) {
## ステータスコードとの使い分け ## ステータスコードとの使い分け
`res`が truthy でも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。 `res`がtruthyでも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
```cpp ```cpp
auto res = cli.Get("/api/data"); auto res = cli.Get("/api/data");
+8 -3
View File
@@ -24,19 +24,24 @@ if (!res) {
} }
``` ```
`ssl_error()`はSSLライブラリが返したエラーコード(OpenSSLの`SSL_get_error()`の値など)、`ssl_backend_error()`はバックエンドがさらに詳しく提供するエラー値です。OpenSSLなら`ERR_get_error()`の値が入ります。 `ssl_error()`は、どのTLSバックエンドでも共通のエラー種別(`httplib::tls::ErrorCode`)を`int`で返します。`ssl_backend_error()`は、バックエンドが返したエラー値そのものです。OpenSSLなら、ハンドシェイクの失敗では`ERR_get_error()`の値が、証明書検証の失敗では検証結果のコード(`X509_V_ERR_*`)が入ります。
## OpenSSLのエラーを文字列化する ## OpenSSLのエラーを文字列化する
`ssl_backend_error()`で取得した値を、OpenSSLの`ERR_error_string()`で文字列にするとデバッグに便利です。 `ssl_backend_error()`の値は、OpenSSLの関数で文字列にしておくとデバッグに便利です。使う関数は失敗の種類によって変わります。
```cpp ```cpp
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/x509.h>
if (res.ssl_backend_error() != 0) { if (res.error() == httplib::Error::SSLConnection) {
char buf[256]; char buf[256];
ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf)); ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf));
std::cerr << "openssl: " << buf << std::endl; 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;
} }
``` ```
+3 -3
View File
@@ -25,7 +25,7 @@ sse.start(); // ブロッキング
## イベント名で分岐する ## イベント名で分岐する
サーバー側で`event:`を付けて送られてくる場合は、`on_event()`で名前ごとにハンドラを登録できます。 サーバーが`event:`を付けてイベントを送ってくる場合は、`on_event()`で名前ごとにハンドラを登録できます。
```cpp ```cpp
sse.on_event("message", [](const auto &msg) { sse.on_event("message", [](const auto &msg) {
@@ -41,7 +41,7 @@ sse.on_event("leave", [](const auto &msg) {
}); });
``` ```
`on_message()`は、名前なし(デフォルトの`message`イベント)を受け取る汎用ハンドラとして使えます。 `on_message()`は、`on_event()`で登録していない名前のイベントをまとめて受け取る汎用ハンドラです。上の例のように`on_event("message", ...)`を登録した場合、`message`イベントは`on_message()`ではなくそちらに届きます。
## 接続イベントとエラーハンドリング ## 接続イベントとエラーハンドリング
@@ -55,7 +55,7 @@ sse.on_error([](httplib::Error err) {
}); });
``` ```
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。 接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。ただし、サーバーが204、403、404のいずれかを返したときは再接続しません。
## 非同期で動かす ## 非同期で動かす
@@ -14,7 +14,7 @@ svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080); svr.listen("0.0.0.0", 8080);
``` ```
`./public/index.html`が`http://localhost:8080/index.html`で、`./public/css/style.css`が`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。 `./public/index.html`には`http://localhost:8080/index.html`で、`./public/css/style.css`には`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。
## 複数のマウントポイント ## 複数のマウントポイント
@@ -26,11 +26,11 @@ svr.set_mount_point("/assets", "./dist/assets");
svr.set_mount_point("/uploads", "./var/uploads"); svr.set_mount_point("/uploads", "./var/uploads");
``` ```
同じパスに複数のマウントを登録することもできます。その場合は登録順に探されて、見つかった最初のものが返ります。 同じパスに複数のマウントを登録することもできます。その場合は登録した順に探し、最初に見つかったファイルを返します。
## APIハンドラと組み合わせる ## APIハンドラと組み合わせる
静的ファイルとAPIハンドラは共存できます。`Get()`などで登録したハンドラが優先され、マッチしなかったときにマウントポイントが探されます。 静的ファイルとAPIハンドラは共存できます。GETとHEADのリクエストでは、まずマウントポイントからファイルを探し、見つからなければ`Get()`などで登録したハンドラを呼びます。
```cpp ```cpp
svr.Get("/api/users", [](const auto &req, auto &res) { svr.Get("/api/users", [](const auto &req, auto &res) {
@@ -44,7 +44,7 @@ svr.set_mount_point("/", "./public");
## MIMEタイプを追加する ## MIMEタイプを追加する
拡張子からContent-Typeを決めるマッピングは組み込みですが、カスタムの拡張子を追加できます。 拡張子からContent-Typeを決める対応表は組み込まれていますが、独自の拡張子を追加することもできます。
```cpp ```cpp
svr.set_file_extension_and_mimetype_mapping("wasm", "application/wasm"); 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( res.set_content_provider(
total_size, "application/octet-stream", total_size, "application/octet-stream",
[](size_t offset, size_t length, httplib::DataSink &sink) { [](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()); sink.write(data.data(), data.size());
return true; return true;
}); });
}); });
``` ```
ラムダが呼ばれるたびに`offset`と`length`が渡されるので、その範囲だけ読み込んで`sink.write()`で送ります。メモリには常に少量のチャンクしか載りません。 ラムダは繰り返し呼ばれ、そのたびに`offset`(ここまでに送った位置)と`length`(残りのバイト数)が渡されます。`length`は残り全部を指すので、上の例のように1回に読む量を自分で区切って`sink.write()`で送ります。こうすれば、メモリに載るのは常に小さなチャンクだけです。
## ファイルをそのまま返す ## ファイルをそのまま返す
@@ -96,7 +96,7 @@ svr.Post("/upload",
}); });
``` ```
`content_reader`が`false`を返したら、レスポンスのステータスは自分でセットしてください。ボディの残りは読まずに接続を閉じるので、送信中のクライアントには接続が切れたように見えます。 `content_reader`が`false`を返した場合、何もしなければステータスは400になります(ボディがサイズ上限を超えていたときは413)。ほかのステータスを返したいときは自分でセットしてください。ボディの残りは読まずに接続を閉じるので、送信中のクライアントには接続が切れたように見えます。
> **Warning:** `HandlerWithContentReader`を使うと、`req.body`は**空のまま**です。ボディはコールバック内で自分で処理してください。 > **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`で決まります。 どちらの境界も`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()`を使ってください。 なお`set_content_provider()`で登録したコンテンツプロバイダは対象外です。圧縮器を通すと、内部バッファが埋まるまで書き込みが送出されず、ボディを少しずつ生成するプロバイダが止まってしまうためです。生成したボディを圧縮したい場合は`set_chunked_content_provider()`を使ってください。
@@ -37,6 +37,8 @@ svr.set_pre_request_handler(
`matched_route`はパスパラメーターを展開する**前**のパターン文字列(例: `/admin/users/:id`)です。特定の値ではなく、ルート定義のパターンで判定できるので、IDや名前に左右されません。 `matched_route`はパスパラメーターを展開する**前**のパターン文字列(例: `/admin/users/:id`)です。特定の値ではなく、ルート定義のパターンで判定できるので、IDや名前に左右されません。
`svr.WebSocket()`で登録したルートでも、Pre-requestハンドラは呼ばれます。呼ばれるのは`101 Switching Protocols`を返す前なので、`Handled`を返すとそのHTTPレスポンス(403など)がそのまま返り、WebSocketへのアップグレードは行われません。
## 戻り値の意味 ## 戻り値の意味
Pre-routingハンドラと同じく、`HandlerResponse`を返します。 Pre-routingハンドラと同じく、`HandlerResponse`を返します。
+2 -2
View File
@@ -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 ```cpp
res.user_data.set("user_id", std::string{"42"}); 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`で取ろうとすると失敗します。 > **Warning:** `user_data.get<T>()`は型が一致しないと`nullptr`を返します。保存時と取得時で同じ型を指定してください。`AuthUser`で入れて`const AuthUser`で取ろうとすると失敗します。
@@ -48,7 +48,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled; 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 *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
auto elapsed = start auto elapsed = start
? std::chrono::duration_cast<std::chrono::milliseconds>( ? std::chrono::duration_cast<std::chrono::milliseconds>(
@@ -43,15 +43,40 @@ svr.listen_after_bind();
## 戻り値のチェック ## 戻り値のチェック
`bind_to_port()`は失敗すると`false`を返します。ポートが既に使われている場合などです。必ずチェックしてください。 `bind_to_port()`は失敗すると`false`を返します。ポートにbindする権限が無い場合などです。必ずチェックしてください。
```cpp ```cpp
if (!svr.bind_to_port("0.0.0.0", 8080)) { 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; return 1;
} }
``` ```
`listen_after_bind()`はサーバーが停止するまでブロックし、正常終了なら`true`を返します。 `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()`の組み合わせです。 > **Note:** 空いているポートを自動で選びたいときは[S17. ポートを動的に割り当てる](../s17-bind-any-port)を参照してください。こちらも内部では`bind_to_any_port()` + `listen_after_bind()`の組み合わせです。
@@ -52,6 +52,6 @@ int main() {
## 処理中のリクエストの扱い ## 処理中のリクエストの扱い
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに処理中のリクエストは**最後まで実行**されます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。 `stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに動いているハンドラは**最後まで実行**されます。ただし、ストリーミングのようにコンテンツプロバイダで送っている途中のレスポンスは、その場で打ち切られます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
> **Warning:** `stop()`を呼んでから`listen()`が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。 > **Warning:** `stop()`を呼んでから`listen()`が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。
@@ -19,7 +19,7 @@ svr.Get("/", [](const auto &, auto &res) {
svr.listen("/tmp/httplib.sock", 80); 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`以外の適当な値を渡してください。
## クライアント側 ## クライアント側
+1 -1
View File
@@ -55,7 +55,7 @@ httplib::SSLClient cli("api.example.com", 443,
auto res = cli.Get("/"); 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からクライアント証明書を設定できます。 クライアント側にも同じ`PemMemory`構造体があり、メモリ上のPEMからクライアント証明書を設定できます。
@@ -31,11 +31,12 @@ int main() {
`svr.WebSocket()`でWebSocket用のハンドラを登録します。ハンドラが呼ばれた時点で、すでにWebSocketのハンドシェイクは完了しています。ループの中で`ws.read()`して`ws.send()`するだけで、エコー動作が完成します。 `svr.WebSocket()`でWebSocket用のハンドラを登録します。ハンドラが呼ばれた時点で、すでにWebSocketのハンドシェイクは完了しています。ループの中で`ws.read()`して`ws.send()`するだけで、エコー動作が完成します。
`read()`の返り値は`ReadResult`列挙値で、次の3種類です。 `read()`の返り値は`ReadResult`列挙値で、次の4種類です。
- `ReadResult::Text`: テキストメッセージを受信 - `ReadResult::Text`: テキストメッセージを受信
- `ReadResult::Binary`: バイナリメッセージを受信 - `ReadResult::Binary`: バイナリメッセージを受信
- `ReadResult::Fail`: エラー、または接続が閉じた - `ReadResult::Fail`: エラー、または接続が閉じた
- `ReadResult::Timeout`: `set_read_timeout()`で自分が設定した読み取りタイムアウトが、何も受信しないまま経過した。接続は開いたまま。コンパイル時のデフォルトのタイムアウトは接続を閉じ、`Fail`として返る([W06. タイムアウトを設定する](../w06-websocket-timeouts)を参照)
## クライアント: エコーを叩く ## クライアント: エコーを叩く
@@ -41,7 +41,7 @@ cli.connect();
デフォルトのPing間隔は、ビルド時のマクロ`CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`で決まります。通常はそのままで問題ありませんが、特別なプロキシ環境に合わせて短くしたい場合は調整してください。 デフォルトのPing間隔は、ビルド時のマクロ`CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`で決まります。通常はそのままで問題ありませんが、特別なプロキシ環境に合わせて短くしたい場合は調整してください。
## PongはどうやってpIngに応答するか ## Pingへの応答(Pong)
WebSocketプロトコルでは、PingフレームにはPongフレームで応答することが決まっています。cpp-httplibは受信したPingに自動でPongを返すので、アプリケーションコード側で気にする必要はありません。 WebSocketプロトコルでは、PingフレームにはPongフレームで応答することが決まっています。cpp-httplibは受信したPingに自動でPongを返すので、アプリケーションコード側で気にする必要はありません。
@@ -55,7 +55,7 @@ WebSocketプロトコルでは、PingフレームにはPongフレームで応答
短すぎると無駄なトラフィックになり、長すぎると接続が切れます。だいたい**接続が切れる時間の半分**くらいが目安です。 短すぎると無駄なトラフィックになり、長すぎると接続が切れます。だいたい**接続が切れる時間の半分**くらいが目安です。
> **Warning:** Ping間隔を極端に短くすると、WebSocket接続ごとにバックグラウンドでスレッドが走るので、CPU負荷が上がります。接続数が多いサーバーでは控えめな値に設定しましょう。 > **Warning:** WebSocket接続ごとにバックグラウンドでスレッドが走るので、Ping間隔を極端に短くするとCPU負荷が上がります。接続数が多いサーバーでは控えめな値に設定しましょう。
## 無応答のピアを検出する ## 無応答のピアを検出する
@@ -67,14 +67,14 @@ cli.set_websocket_max_missed_pongs(2); // 2回連続でPongが返ってこなけ
サーバー側にも同じ`set_websocket_max_missed_pongs()`があります。 サーバー側にも同じ`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`以上を設定してください。 `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)を参照してください。 > 接続が閉じたときの処理は[W03. 接続クローズをハンドリングする](../w03-websocket-close)を参照してください。
@@ -42,6 +42,9 @@ switch (result) {
case httplib::ws::ReadResult::Fail: case httplib::ws::ReadResult::Fail:
// エラーまたは切断 // エラーまたは切断
break; break;
case httplib::ws::ReadResult::Timeout:
// 読み取りタイムアウト。接続は開いたまま
break;
} }
``` ```
@@ -9,7 +9,7 @@ status: "draft"
| 種類 | API | デフォルト | | 種類 | API | デフォルト |
| --- | --- | --- | | --- | --- | --- |
| 接続タイムアウト | `set_connection_timeout` | 300秒 | | 接続タイムアウト | `set_connection_timeout` | 300秒 |
| 読み取りタイムアウト | `set_read_timeout` | 300秒(`CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND`) | | 読み取りタイムアウト | `set_read_timeout` | なし。無期限に待つ(`CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND`) |
| 書き込みタイムアウト | `set_write_timeout` | 5秒 | | 書き込みタイムアウト | `set_write_timeout` | 5秒 |
## 基本の使い方 ## 基本の使い方
@@ -26,7 +26,7 @@ if (ws.connect()) {
} }
``` ```
`connect()`を呼ぶ前に設定してください。 接続タイムアウトと書き込みタイムアウトは`connect()`を呼ぶ前に設定してください。読み取りタイムアウトはいつでも変更でき、接続済みの状態で設定した場合は次の`read()`から効きます。
## `std::chrono`で指定する ## `std::chrono`で指定する
@@ -40,9 +40,44 @@ ws.set_read_timeout(30s);
ws.set_write_timeout(10s); ws.set_write_timeout(10s);
``` ```
## 読み取りタイムアウトの意味に注意 ## 読み取りタイムアウトの意味
`set_read_timeout()`は「1回の`read()`呼び出し」に対するタイムアウトです。メッセージが届かないまま指定時間が経過すると`read()`が`ReadResult::Fail`を返します。通知の待受のように長時間メッセージが来ないことが正常な接続では、意図せず切断されないよう長めに設定するか、切断されたらアプリケーション側で再接続してください。 `set_read_timeout()`は「1回の`read()`呼び出し」に対するタイムアウトです。メッセージが届かないまま指定時間が経過すると`read()`は`ReadResult::Timeout`を返します。このとき**接続は開いたまま**で、1バイトも読み進めていないので、そのまま送信して読み直せます。接続が失われたことを意味する`ReadResult::Fail`とはここが違います。
1本の接続を1つのスレッドで双方向に扱えるのはこのためです。
```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); // 何も届いていない。溜まっている分を送る
continue;
}
if (r == httplib::ws::Fail) { break; }
handle(msg);
}
```
読み取りタイムアウトを設定しないと`read()`はメッセージが届くまで戻らないので、接続を持っているスレッドは送信に手が回りません。
`Timeout`について2点あります。
- `msg`は書き換えられません。値も0以外なので、読み取りタイムアウトを設定した状態で`while (ws.read(msg))`と書くと、**前回のメッセージ**が`msg`に残ったままループが回り続けます。
- 報告されるのはメッセージの境界だけです。分割されたメッセージの途中でタイムアウトした場合、そのメッセージは再開できないので`read()`は`Fail`を返します。
通知の待受のように長時間メッセージが来ないことが正常な接続では、読み取りタイムアウトを設定しないままにするか、`Timeout`を「まだ何も来ていない」印として扱ってループを続けてください。
## サーバ側
ハンドラが受け取る`ws::WebSocket`にも`set_read_timeout()`があります。ハンドラが`read()`で止まったままにならないので、上と同じ書き方で複数の接続の間をメッセージが中継できます。
サーバ側のデフォルトは「無期限」ではなく300秒(`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`)です。WebSocketのハンドラは接続が続く限りワーカーを1つ占有するので、無言になったピアからワーカーを回収する保険として働きます。
この保険はハンドラが求めたタイムアウトではないので、`Timeout`としては返りません。経過すると`read()`は`Fail`を返して接続を閉じるため、`while (ws.read(msg))`と書いたハンドラは従来どおりそこで終わります。`Timeout`が返るのは、ハンドラ自身が`set_read_timeout()`で設定したタイムアウトだけです。
> Ping/Pongによる無応答ピア検出は別の仕組みです。詳しくは[W02. ハートビートを設定する](../w02-websocket-ping)を参照してください。 > Ping/Pongによる無応答ピア検出は別の仕組みです。詳しくは[W02. ハートビートを設定する](../w02-websocket-ping)を参照してください。
+1 -1
View File
@@ -3,7 +3,7 @@ title: "cpp-httplib"
order: 0 order: 0
--- ---
[cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h) というヘッダーファイルを1枚コピーするだけで使えます。 [cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h)というヘッダーファイルを1枚コピーするだけで使えます。
C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。 C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。
+1 -9
View File
@@ -18,10 +18,6 @@ llama.cppのAPIを直接扱うとコードが長くなるので、薄いラッ
int main() { int main() {
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"}; auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// ... HTTPサーバーの構築・起動 ... // ... HTTPサーバーの構築・起動 ...
} }
``` ```
@@ -78,7 +74,7 @@ svr.Post("/translate",
}); });
``` ```
`llm.chat()`は推論中に例外を投げることがあります(コンテキスト長の超過など)。`try/catch`で捕捉してエラーをJSONで返すことで、サーバーがクラッシュするのを防ぎます。 `llm.chat()`は推論中に例外を投げることがあります(コンテキスト長の超過など)。`try/catch`で捕捉して、エラーの内容をJSONで返します。捕捉しなくてもcpp-httplibが500を返してくれますが、何が起きたのかはクライアントに伝わりません。
## 2.3 全体のコード ## 2.3 全体のコード
@@ -111,10 +107,6 @@ int main() {
// 1章でダウンロードしたモデルをロード // 1章でダウンロードしたモデルをロード
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"}; auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// リクエストとレスポンスをログに記録 // リクエストとレスポンスをログに記録
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
@@ -73,7 +73,7 @@ svr.Post("/translate/stream",
- `sink.os`に書き込んだ後、`sink.os.good()`でクライアントがまだ接続しているかを確認できます。切断されていたら`false`を返して推論を止めます - `sink.os`に書き込んだ後、`sink.os.good()`でクライアントがまだ接続しているかを確認できます。切断されていたら`false`を返して推論を止めます
- 各トークンは`json(token).dump()`でJSON文字列としてエスケープしてから送ります。改行やクォートを含むトークンでも安全です - 各トークンは`json(token).dump()`でJSON文字列としてエスケープしてから送ります。改行やクォートを含むトークンでも安全です
- `dump(-1, ' ', false, ...)`の最初の3つの引数はデフォルトと同じです。重要なのは第4引数の`json::error_handler_t::replace`です。LLMはトークンをサブワード単位で返すため、マルチバイト文字(日本語など)の途中でトークンが切れることがあります。不完全なUTF-8バイト列をそのまま`dump()`に渡すと例外が飛ぶので、`replace`で安全に置換します。ブラウザ側で結合されるため、表示上の問題はありません - `dump(-1, ' ', false, ...)`の最初の3つの引数はデフォルトと同じです。重要なのは第4引数の`json::error_handler_t::replace`です。LLMはトークンをサブワード単位で返すため、マルチバイト文字(日本語など)の途中でトークンが切れることがあります。不完全なUTF-8バイト列をそのまま`dump()`に渡すと例外が飛ぶので、`replace`で安全に置換します。ブラウザ側で結合されるため、表示上の問題はありません
- `try/catch`でラムダ全体を囲んでいます。`llm.chat()`はコンテキストウィンドウの超過などで例外を投げることがあります。ラムダ内で例外が未捕捉だとサーバーがクラッシュするので、エラーをSSEイベントとして返します - `try/catch`でラムダ全体を囲んでいます。`llm.chat()`はコンテキストウィンドウの超過などで例外を投げることがあります。ラムダの中で例外を捕捉しないと、cpp-httplibは接続を切るだけなので、何が起きたのかクライアントにはわかりません。そこで、エラーをSSEイベントとして返します
- `data: [DONE]`はOpenAI APIと同じ慣習で、ストリームの終了をクライアントに伝えます - `data: [DONE]`はOpenAI APIと同じ慣習で、ストリームの終了をクライアントに伝えます
## 3.4 全体のコード ## 3.4 全体のコード
@@ -107,10 +107,6 @@ int main() {
// GGUFモデルをロード // GGUFモデルをロード
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"}; auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// リクエストとレスポンスをログに記録 // リクエストとレスポンスをログに記録
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
@@ -219,7 +219,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); cli.set_follow_location(true);
cli.set_read_timeout(std::chrono::hours(1));
auto url = "/" + model.repo + "/resolve/main/" + model.filename; auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / 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) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
auto url = "/" + model.repo + "/resolve/main/" + model.filename; auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename; auto path = get_models_dir() / model.filename;
@@ -539,10 +537,6 @@ int main() {
auto llm = llamalib::Llama{path}; auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl; << std::endl;
-5
View File
@@ -939,7 +939,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
auto url = "/" + model.repo + "/resolve/main/" + model.filename; auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename; auto path = get_models_dir() / model.filename;
@@ -1008,10 +1007,6 @@ int main() {
} }
auto llm = llamalib::Llama{path}; auto llm = llamalib::Llama{path};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl; << std::endl;
@@ -17,7 +17,7 @@ order: 6
モデルは初回起動時に自動ダウンロードされるので、ユーザーに渡すのはバイナリ1つだけです。 モデルは初回起動時に自動ダウンロードされるので、ユーザーに渡すのはバイナリ1つだけです。
## 6.1 webview/webview を導入する ## 6.1 webview/webviewを導入する
[webview/webview](https://github.com/webview/webview)は、OS標準のWebViewコンポーネント(macOSならWKWebView、LinuxならWebKitGTK、WindowsならWebView2)をC/C++から使えるようにするライブラリです。Electronのように独自ブラウザを同梱するわけではないので、バイナリサイズへの影響はほぼありません。 [webview/webview](https://github.com/webview/webview)は、OS標準のWebViewコンポーネント(macOSならWKWebView、LinuxならWebKitGTK、WindowsならWebView2)をC/C++から使えるようにするライブラリです。Electronのように独自ブラウザを同梱するわけではないので、バイナリサイズへの影響はほぼありません。
@@ -78,7 +78,7 @@ int main() {
5章の`signal_handler`は不要になります。デスクトップアプリではウインドウを閉じることがアプリの終了を意味するからです。 5章の`signal_handler`は不要になります。デスクトップアプリではウインドウを閉じることがアプリの終了を意味するからです。
## 6.3 cpp-embedlib で静的ファイルを埋め込む ## 6.3 cpp-embedlibで静的ファイルを埋め込む
5章では`public/`ディレクトリからファイルを配信していました。これだと配布時に`public/`も一緒に渡す必要があります。[cpp-embedlib](https://github.com/yhirose/cpp-embedlib)を使うと、HTML・CSS・JavaScriptをバイナリに埋め込んで、配布物をバイナリ1つにまとめられます。 5章では`public/`ディレクトリからファイルを配信していました。これだと配布時に`public/`も一緒に渡す必要があります。[cpp-embedlib](https://github.com/yhirose/cpp-embedlib)を使うと、HTML・CSS・JavaScriptをバイナリに埋め込んで、配布物をバイナリ1つにまとめられます。
@@ -108,7 +108,7 @@ target_link_libraries(translate-app PRIVATE
`cpp_embedlib_add`は、`public/`配下のファイルをコンパイル時にバイナリに変換し、`WebAssets`という静的ライブラリを作ります。リンクすると`Web::FS`というオブジェクトから埋め込みファイルにアクセスできます。`cpp-embedlib-httplib`は`httplib::mount()`関数を提供するヘルパーライブラリです。 `cpp_embedlib_add`は、`public/`配下のファイルをコンパイル時にバイナリに変換し、`WebAssets`という静的ライブラリを作ります。リンクすると`Web::FS`というオブジェクトから埋め込みファイルにアクセスできます。`cpp-embedlib-httplib`は`httplib::mount()`関数を提供するヘルパーライブラリです。
### set_mount_point を httplib::mount に置き換える ### set_mount_pointをhttplib::mountに置き換える
5章の`set_mount_point`をcpp-embedlibの`httplib::mount`に置き換えるだけです。 5章の`set_mount_point`をcpp-embedlibの`httplib::mount`に置き換えるだけです。
@@ -407,7 +407,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) { std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co"); httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
auto url = "/" + model.repo + "/resolve/main/" + model.filename; auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename; auto path = get_models_dir() / model.filename;
@@ -469,10 +468,6 @@ int main() {
auto llm = llamalib::Llama{path}; auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) { svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl; << std::endl;
+10 -6
View File
@@ -11,13 +11,17 @@ order: 7
## 7.1 ソースコードの場所 ## 7.1 ソースコードの場所
```ascii ```ascii
llama.cpp/tools/server/ llama.cpp/
├── server.cpp # メインのサーバー実装 ├── tools/server/
├── httplib.h # cpp-httplib(同梱版) │ ├── server.cpp # エントリポイント
└── ... │ ├── server-http.cpp # HTTPサーバー(cpp-httplibを使う層)
│ ├── server-context.cpp # 推論とスロットの管理
│ └── ...
└── vendor/cpp-httplib/
└── httplib.h # cpp-httplib(同梱版)
``` ```
ファイルは1つの`server.cpp`にまとまっています。数千行ありますが、構造を知っていれば読むべき箇所は絞れます。 実装は役割ごとにファイルが分かれています。全体では2万行を超えますが、構造を知っていれば読むべき箇所は絞れます。
## 7.2 OpenAI互換API ## 7.2 OpenAI互換API
@@ -141,7 +145,7 @@ LLMをアプリに組み込むとき、出力を確実にパースできるか
| SSEフォーマット | トークンのみ | OpenAI互換JSON | | SSEフォーマット | トークンのみ | OpenAI互換JSON |
| KVキャッシュ | 毎回クリア | prefixを再利用 | | KVキャッシュ | 毎回クリア | prefixを再利用 |
| 構造化出力 | なし | JSON Schema/文法制約 | | 構造化出力 | なし | JSON Schema/文法制約 |
| コード量 | 約200行 | 数千行 | | コード量 | 約200行 | 2万行以上 |
私たちのコードがシンプルなのは、「デスクトップアプリで1人が使う」という前提があるからです。複数人に提供するサーバーや、既存のエコシステムと連携するサーバーを作るなら、`llama-server`の設計が参考になります。 私たちのコードがシンプルなのは、「デスクトップアプリで1人が使う」という前提があるからです。複数人に提供するサーバーや、既存のエコシステムと連携するサーバーを作るなら、`llama-server`の設計が参考になります。
@@ -113,7 +113,7 @@ CI(GitHub Actionsなど)でクロスプラットフォームビルドを自
- **クライアント**: HTTPS接続、リダイレクト追従、コンテンツレシーバーによる大容量ダウンロード、進捗コールバック - **クライアント**: HTTPS接続、リダイレクト追従、コンテンツレシーバーによる大容量ダウンロード、進捗コールバック
- **WebView連携**: `bind_to_any_port` + `listen_after_bind`でバックグラウンドスレッド化 - **WebView連携**: `bind_to_any_port` + `listen_after_bind`でバックグラウンドスレッド化
cpp-httplibにはこの他にも、マルチパートによるファイルアップロード、認証、タイムアウト制御、圧縮、レンジリクエストなど便利な機能があります。詳しくは [A Tour of cpp-httplib](../../tour/) をご覧ください。 cpp-httplibにはこの他にも、マルチパートによるファイルアップロード、認証、タイムアウト制御、圧縮、レンジリクエストなど便利な機能があります。詳しくは[A Tour of cpp-httplib](../../tour/)をご覧ください。
これらのパターンは翻訳アプリに限りません。自分のC++ライブラリにWeb APIを付けたい、ブラウザUIで操作できるようにしたい、配布しやすいデスクトップアプリにしたい―そんなときに、この本がリファレンスになれば嬉しいです。 これらのパターンは翻訳アプリに限りません。自分のC++ライブラリにWeb APIを付けたい、ブラウザUIで操作できるようにしたい、配布しやすいデスクトップアプリにしたい―そんなときに、この本がリファレンスになれば嬉しいです。
+9 -9
View File
@@ -5,7 +5,7 @@ order: 1
cpp-httplibを始めるのに必要なのは、`httplib.h`とC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。 cpp-httplibを始めるのに必要なのは、`httplib.h`とC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。
## httplib.h の入手 ## httplib.hの入手
GitHubから直接ダウンロードできます。常に最新版を使ってください。 GitHubから直接ダウンロードできます。常に最新版を使ってください。
@@ -13,19 +13,19 @@ GitHubから直接ダウンロードできます。常に最新版を使って
curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
``` ```
ダウンロードした `httplib.h` をプロジェクトのディレクトリに置けば、準備完了です。 ダウンロードした`httplib.h`をプロジェクトのディレクトリに置けば、準備完了です。
## コンパイラーの準備 ## コンパイラーの準備
| OS | 開発環境 | セットアップ | | OS | 開発環境 | セットアップ |
| -- | -------- | ------------ | | -- | -------- | ------------ |
| macOS | Apple Clang | Xcode Command Line Tools (`xcode-select --install`) | | macOS | Apple Clang | Xcode Command Line Tools (`xcode-select --install`) |
| Ubuntu | clang++ または g++ | `apt install clang` または `apt install g++` | | Ubuntu | clang++またはg++ | `apt install clang`または`apt install g++` |
| Windows | MSVC | Visual Studio 2022 以降(C++ コンポーネントを含めてインストール) | | Windows | MSVC | Visual Studio 2022以降(C++コンポーネントを含めてインストール) |
## Hello World サーバー ## Hello Worldサーバー
次のコードを `server.cpp` として保存しましょう。 次のコードを`server.cpp`として保存しましょう。
```cpp ```cpp
#include "httplib.h" #include "httplib.h"
@@ -70,16 +70,16 @@ cl /EHsc /std:c++17 server.cpp
server.exe server.exe
``` ```
ブラウザで `http://localhost:8080` を開いてください。"Hello, World!" と表示されれば成功です。 ブラウザで`http://localhost:8080`を開いてください。"Hello, World!"と表示されれば成功です。
`curl` でも確認できます。 `curl`でも確認できます。
```sh ```sh
curl http://localhost:8080/ curl http://localhost:8080/
# Hello, World! # Hello, World!
``` ```
サーバーを停止するには、ターミナルで `Ctrl+C` を押します。 サーバーを停止するには、ターミナルで`Ctrl+C`を押します。
## 次のステップ ## 次のステップ
+21 -21
View File
@@ -3,7 +3,7 @@ title: "Basic Client"
order: 2 order: 2
--- ---
cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client` を使って、GETやPOSTリクエストを送ってみましょう。 cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client`を使って、GETやPOSTリクエストを送ってみましょう。
## テスト用サーバーの準備 ## テスト用サーバーの準備
@@ -77,9 +77,9 @@ int main() {
} }
``` ```
`httplib::Client` のコンストラクターにサーバーのアドレスを渡し、`Get()` でリクエストを送ります。戻り値の `res` からステータスコードやボディを取得できます。 `httplib::Client`のコンストラクターにサーバーのアドレスを渡し、`Get()`でリクエストを送ります。戻り値の`res`からステータスコードやボディを取得できます。
対応する `curl` コマンドはこうなります。 対応する`curl`コマンドはこうなります。
```sh ```sh
curl http://localhost:8080/hi curl http://localhost:8080/hi
@@ -104,11 +104,11 @@ if (res) {
} }
``` ```
`res->body` は `std::string` なので、JSON レスポンスをパースしたい場合は [nlohmann/json](https://github.com/nlohmann/json) などの JSON ライブラリにそのまま渡せます。 `res->body`は`std::string`なので、JSONレスポンスをパースしたい場合は[nlohmann/json](https://github.com/nlohmann/json)などのJSONライブラリにそのまま渡せます。
## クエリパラメーター ## クエリパラメーター
GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params` を使います。 GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params`を使います。
```cpp ```cpp
auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}}); auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
@@ -117,7 +117,7 @@ if (res) {
} }
``` ```
`httplib::Params` を使うと、特殊文字のURLエンコードを自動で行ってくれます。 `httplib::Params`を使うと、特殊文字のURLエンコードを自動で行ってくれます。
```sh ```sh
curl "http://localhost:8080/search?q=cpp-httplib" curl "http://localhost:8080/search?q=cpp-httplib"
@@ -126,7 +126,7 @@ curl "http://localhost:8080/search?q=cpp-httplib"
## パスパラメーター ## パスパラメーター
URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま `Get()` に渡すだけです。 URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま`Get()`に渡すだけです。
```cpp ```cpp
auto res = cli.Get("/users/42"); auto res = cli.Get("/users/42");
@@ -140,7 +140,7 @@ curl http://localhost:8080/users/42
# User ID: 42 # User ID: 42
``` ```
テスト用サーバーには、正規表現でIDを数字のみに絞った `/files/(\d+)` もあります。 テスト用サーバーには、正規表現でIDを数字のみに絞った`/files/(\d+)`もあります。
```cpp ```cpp
auto res = cli.Get("/files/42"); auto res = cli.Get("/files/42");
@@ -154,11 +154,11 @@ curl http://localhost:8080/files/42
# File ID: 42 # File ID: 42
``` ```
`/files/abc` のように数字以外を渡すと404が返ります。仕組みは次章で解説します。 `/files/abc`のように数字以外を渡すと404が返ります。仕組みは次章で解説します。
## リクエストヘッダー ## リクエストヘッダー
カスタムHTTPヘッダーを付けるには、`httplib::Headers` を渡します。`Get()` や `Post()` のどちらでも使えます。 カスタムHTTPヘッダーを付けるには、`httplib::Headers`を渡します。`Get()`や`Post()`のどちらでも使えます。
```cpp ```cpp
auto res = cli.Get("/hi", httplib::Headers{ auto res = cli.Get("/hi", httplib::Headers{
@@ -172,7 +172,7 @@ curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
## POSTリクエスト ## POSTリクエスト
テキストデータをPOSTしてみましょう。`Post()` の第2引数にボディ、第3引数にContent-Typeを指定します。 テキストデータをPOSTしてみましょう。`Post()`の第2引数にボディ、第3引数にContent-Typeを指定します。
```cpp ```cpp
auto res = cli.Post("/post", "Hello, Server!", "text/plain"); auto res = cli.Post("/post", "Hello, Server!", "text/plain");
@@ -182,7 +182,7 @@ if (res) {
} }
``` ```
テスト用サーバーの `/post` はボディをそのまま返すので、送った文字列がそのまま返ってきます。 テスト用サーバーの`/post`はボディをそのまま返すので、送った文字列がそのまま返ってきます。
```sh ```sh
curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
@@ -191,7 +191,7 @@ curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:
## フォームデータの送信 ## フォームデータの送信
HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params` を使います。 HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params`を使います。
```cpp ```cpp
auto res = cli.Post("/submit", httplib::Params{ auto res = cli.Post("/submit", httplib::Params{
@@ -200,12 +200,12 @@ auto res = cli.Post("/submit", httplib::Params{
}); });
if (res) { if (res) {
std::cout << res->body << std::endl; std::cout << res->body << std::endl;
// age = 30
// name = Alice // name = Alice
// age = 30
} }
``` ```
これは `application/x-www-form-urlencoded` 形式で送信されます。 これは`application/x-www-form-urlencoded`形式で送信されます。
```sh ```sh
curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
@@ -213,7 +213,7 @@ curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
## ファイルのPOST ## ファイルのPOST
ファイルをアップロードするには、`httplib::UploadFormDataItems` を使ってマルチパートフォームデータとして送信します。 ファイルをアップロードするには、`httplib::UploadFormDataItems`を使ってマルチパートフォームデータとして送信します。
```cpp ```cpp
auto res = cli.Post("/upload", httplib::UploadFormDataItems{ auto res = cli.Post("/upload", httplib::UploadFormDataItems{
@@ -224,7 +224,7 @@ if (res) {
} }
``` ```
`UploadFormDataItems` の各要素は `{name, content, filename, content_type}` の4つのフィールドで構成されます。 `UploadFormDataItems`の各要素は`{name, content, filename, content_type}`の4つのフィールドで構成されます。
```sh ```sh
curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
@@ -232,7 +232,7 @@ curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:
## エラーハンドリング ## エラーハンドリング
ネットワーク通信では、サーバーに接続できない場合があります。`res` が有効かどうかを必ず確認しましょう。 ネットワーク通信では、サーバーに接続できない場合があります。`res`が有効かどうかを必ず確認しましょう。
```cpp ```cpp
httplib::Client cli("http://localhost:9999"); // 存在しないポート httplib::Client cli("http://localhost:9999"); // 存在しないポート
@@ -241,7 +241,7 @@ auto res = cli.Get("/hi");
if (!res) { if (!res) {
// 接続エラー // 接続エラー
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl; std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
// Error: Connection // Error: Could not establish connection
return 1; return 1;
} }
@@ -256,8 +256,8 @@ std::cout << res->body << std::endl;
エラーには2つのレベルがあります。 エラーには2つのレベルがあります。
- **接続エラー**: サーバーに到達できなかった場合。`res` が偽になり、`res.error()` でエラーの種類を取得できます - **接続エラー**: サーバーに到達できなかった場合。`res`が偽になり、`res.error()`でエラーの種類を取得できます
- **HTTPエラー**: サーバーからエラーステータス(404、500など)が返ってきた場合。`res` は真ですが、`res->status` を確認する必要があります - **HTTPエラー**: サーバーからエラーステータス(404、500など)が返ってきた場合。`res`は真ですが、`res->status`を確認する必要があります
## 次のステップ ## 次のステップ
+28 -28
View File
@@ -7,15 +7,15 @@ order: 3
## サーバーの起動 ## サーバーの起動
ルーティングを登録したら、最後に `svr.listen()` を呼んでサーバーを起動します。 ルーティングを登録したら、最後に`svr.listen()`を呼んでサーバーを起動します。
```cpp ```cpp
svr.listen("0.0.0.0", 8080); svr.listen("0.0.0.0", 8080);
``` ```
第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"` を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは `"127.0.0.1"` を使います。 第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"`を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは`"127.0.0.1"`を使います。
`listen()` はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで `Ctrl+C` を押すか、別スレッドから `svr.stop()` を呼ぶまでサーバーは動き続けます。 `listen()`はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで`Ctrl+C`を押すか、別スレッドから`svr.stop()`を呼ぶまでサーバーは動き続けます。
## ルーティング ## ルーティング
@@ -29,7 +29,7 @@ svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
}); });
``` ```
`svr.Get()` は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。`/hi` にGETリクエストが来たら、このラムダが呼ばれます。 `svr.Get()`は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。`/hi`にGETリクエストが来たら、このラムダが呼ばれます。
HTTPメソッドごとにメソッドが用意されています。 HTTPメソッドごとにメソッドが用意されています。
@@ -40,7 +40,7 @@ svr.Put("/path", handler); // PUT
svr.Delete("/path", handler); // DELETE svr.Delete("/path", handler); // DELETE
``` ```
ハンドラーのシグネチャは `(const httplib::Request &req, httplib::Response &res)` です。`auto` を使って短く書くこともできます。 ハンドラーのシグネチャは`(const httplib::Request &req, httplib::Response &res)`です。`auto`を使って短く書くこともできます。
```cpp ```cpp
svr.Get("/hi", [](const auto &req, auto &res) { svr.Get("/hi", [](const auto &req, auto &res) {
@@ -52,11 +52,11 @@ svr.Get("/hi", [](const auto &req, auto &res) {
## リクエストオブジェクト ## リクエストオブジェクト
ハンドラーの第1引数 `req` から、クライアントが送ってきた情報を読み取れます。 ハンドラーの第1引数`req`から、クライアントが送ってきた情報を読み取れます。
### ボディ ### ボディ
`req.body` でリクエストボディを取得できます。型は `std::string` です。 `req.body`でリクエストボディを取得できます。型は`std::string`です。
```cpp ```cpp
svr.Post("/post", [](const auto &req, auto &res) { svr.Post("/post", [](const auto &req, auto &res) {
@@ -67,7 +67,7 @@ svr.Post("/post", [](const auto &req, auto &res) {
### ヘッダー ### ヘッダー
`req.get_header_value()` でリクエストヘッダーの値を取得できます。 `req.get_header_value()`でリクエストヘッダーの値を取得できます。
```cpp ```cpp
svr.Get("/check", [](const auto &req, auto &res) { svr.Get("/check", [](const auto &req, auto &res) {
@@ -78,7 +78,7 @@ svr.Get("/check", [](const auto &req, auto &res) {
### クエリパラメーターとフォームデータ ### クエリパラメーターとフォームデータ
`req.get_param_value()` でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。 `req.get_param_value()`でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。
```cpp ```cpp
svr.Get("/search", [](const auto &req, auto &res) { svr.Get("/search", [](const auto &req, auto &res) {
@@ -87,9 +87,9 @@ svr.Get("/search", [](const auto &req, auto &res) {
}); });
``` ```
`/search?q=cpp-httplib` にアクセスすると、`q` の値は `"cpp-httplib"` になります。 `/search?q=cpp-httplib`にアクセスすると、`q`の値は`"cpp-httplib"`になります。
すべてのパラメーターをループで処理したいときは、`req.params` を使います。 すべてのパラメーターをループで処理したいときは、`req.params`を使います。
```cpp ```cpp
svr.Post("/submit", [](const auto &req, auto &res) { svr.Post("/submit", [](const auto &req, auto &res) {
@@ -103,7 +103,7 @@ svr.Post("/submit", [](const auto &req, auto &res) {
### ファイルアップロード ### ファイルアップロード
マルチパートフォームでアップロードされたファイルは、`req.form.get_file()` で取得します。 マルチパートフォームでアップロードされたファイルは、`req.form.get_file()`で取得します。
```cpp ```cpp
svr.Post("/upload", [](const auto &req, auto &res) { svr.Post("/upload", [](const auto &req, auto &res) {
@@ -113,11 +113,11 @@ svr.Post("/upload", [](const auto &req, auto &res) {
}); });
``` ```
`f.filename` でファイル名、`f.content` でファイルの中身にアクセスできます。 `f.filename`でファイル名、`f.content`でファイルの中身にアクセスできます。
## パスパラメーター ## パスパラメーター
URLの一部を変数として受け取りたいことがあります。たとえば `/users/42` の `42` を取得したい場合です。`:param` 記法を使うと、URLの一部をキャプチャできます。 URLの一部を変数として受け取りたいことがあります。たとえば`/users/42`の`42`を取得したい場合です。`:param`記法を使うと、URLの一部をキャプチャできます。
```cpp ```cpp
svr.Get("/users/:id", [](const auto &req, auto &res) { svr.Get("/users/:id", [](const auto &req, auto &res) {
@@ -126,7 +126,7 @@ svr.Get("/users/:id", [](const auto &req, auto &res) {
}); });
``` ```
`/users/42` にアクセスすると、`req.path_params.at("id")` は `"42"` を返します。`/users/100` なら `"100"` です。 `/users/42`にアクセスすると、`req.path_params.at("id")`は`"42"`を返します。`/users/100`なら`"100"`です。
複数のパスパラメーターも使えます。 複数のパスパラメーターも使えます。
@@ -140,7 +140,7 @@ svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
### 正規表現パターン ### 正規表現パターン
`:param` の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は `req.matches` で取得します。型は `std::smatch` です。 `:param`の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は`req.matches`で取得します。型は`std::smatch`です。
```cpp ```cpp
// 数字のみのIDを受け付ける // 数字のみのIDを受け付ける
@@ -150,15 +150,15 @@ svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
}); });
``` ```
`/files/42` にはマッチしますが、`/files/abc` にはマッチしません。入力値を絞り込みたいときに便利です。 `/files/42`にはマッチしますが、`/files/abc`にはマッチしません。入力値を絞り込みたいときに便利です。
## レスポンスの組み立て ## レスポンスの組み立て
ハンドラーの第2引数 `res` を使って、クライアントに返すレスポンスを組み立てます。 ハンドラーの第2引数`res`を使って、クライアントに返すレスポンスを組み立てます。
### ボディとContent-Type ### ボディとContent-Type
`res.set_content()` でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。 `res.set_content()`でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。
```cpp ```cpp
svr.Get("/hi", [](const auto &req, auto &res) { svr.Get("/hi", [](const auto &req, auto &res) {
@@ -168,7 +168,7 @@ svr.Get("/hi", [](const auto &req, auto &res) {
### ステータスコード ### ステータスコード
ステータスコードを変えたいときは、`res.status` に代入します。 ステータスコードを変えたいときは、`res.status`に代入します。
```cpp ```cpp
svr.Get("/not-found", [](const auto &req, auto &res) { svr.Get("/not-found", [](const auto &req, auto &res) {
@@ -179,7 +179,7 @@ svr.Get("/not-found", [](const auto &req, auto &res) {
### レスポンスヘッダー ### レスポンスヘッダー
`res.set_header()` でレスポンスヘッダーを追加できます。 `res.set_header()`でレスポンスヘッダーを追加できます。
```cpp ```cpp
svr.Get("/with-header", [](const auto &req, auto &res) { svr.Get("/with-header", [](const auto &req, auto &res) {
@@ -200,7 +200,7 @@ svr.Get("/hi", [](const auto &, auto &res) {
}); });
``` ```
最もシンプルなハンドラーです。リクエストの情報は使わないので、`req` の変数名を省略しています。`"Hello!"` というテキストをそのまま返します。 最もシンプルなハンドラーです。リクエストの情報は使わないので、`req`の変数名を省略しています。`"Hello!"`というテキストをそのまま返します。
### GET /search ### GET /search
@@ -211,7 +211,7 @@ svr.Get("/search", [](const auto &req, auto &res) {
}); });
``` ```
`req.get_param_value("q")` でクエリパラメーター `q` の値を取り出します。`/search?q=cpp-httplib` なら、レスポンスは `"Query: cpp-httplib"` になります。 `req.get_param_value("q")`でクエリパラメーター`q`の値を取り出します。`/search?q=cpp-httplib`なら、レスポンスは`"Query: cpp-httplib"`になります。
### POST /post ### POST /post
@@ -221,7 +221,7 @@ svr.Post("/post", [](const auto &req, auto &res) {
}); });
``` ```
クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body` にボディが丸ごと入っています。 クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body`にボディが丸ごと入っています。
### POST /submit ### POST /submit
@@ -235,7 +235,7 @@ svr.Post("/submit", [](const auto &req, auto &res) {
}); });
``` ```
フォームデータとして送られたキーと値のペアを、`req.params` でループ処理しています。構造化束縛 `auto &[key, val]` を使って、各ペアを取り出しています。 フォームデータとして送られたキーと値のペアを、`req.params`でループ処理しています。構造化束縛`auto &[key, val]`を使って、各ペアを取り出しています。
### POST /upload ### POST /upload
@@ -247,7 +247,7 @@ svr.Post("/upload", [](const auto &req, auto &res) {
}); });
``` ```
マルチパートフォームで送られたファイルを受け取ります。`req.form.get_file("file")` で `"file"` という名前のフィールドを取得し、`f.filename` と `f.content.size()` でファイル名とサイズを返しています。 マルチパートフォームで送られたファイルを受け取ります。`req.form.get_file("file")`で`"file"`という名前のフィールドを取得し、`f.filename`と`f.content.size()`でファイル名とサイズを返しています。
### GET /users/:id ### GET /users/:id
@@ -258,7 +258,7 @@ svr.Get("/users/:id", [](const auto &req, auto &res) {
}); });
``` ```
`:id` の部分がパスパラメーターです。`req.path_params.at("id")` で値を取り出しています。`/users/42` なら `"42"`、`/users/alice` なら `"alice"` が得られます。 `:id`の部分がパスパラメーターです。`req.path_params.at("id")`で値を取り出しています。`/users/42`なら`"42"`、`/users/alice`なら`"alice"`が得られます。
### GET /files/(\d+) ### GET /files/(\d+)
@@ -269,7 +269,7 @@ svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
}); });
``` ```
正規表現 `(\d+)` で数字だけのIDにマッチします。`/files/42` にはマッチしますが、`/files/abc` は404になります。`req.matches[1]` で最初のキャプチャグループの値を取得しています。 正規表現`(\d+)`で数字だけのIDにマッチします。`/files/42`にはマッチしますが、`/files/abc`は404になります。`req.matches[1]`で最初のキャプチャグループの値を取得しています。
## 次のステップ ## 次のステップ
+13 -13
View File
@@ -3,11 +3,11 @@ title: "Static File Server"
order: 4 order: 4
--- ---
cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()` を1行呼ぶだけです。 cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()`を1行呼ぶだけです。
## set_mount_point の基本 ## set_mount_pointの基本
さっそくやってみましょう。`set_mount_point()` は、URLのパスとローカルディレクトリを紐づけます。 さっそくやってみましょう。`set_mount_point()`は、URLのパスとローカルディレクトリを紐づけます。
```cpp ```cpp
#include "httplib.h" #include "httplib.h"
@@ -23,9 +23,9 @@ int main() {
} }
``` ```
第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、`/` へのリクエストを `./html` ディレクトリから配信します。 第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、`/`へのリクエストを`./html`ディレクトリから配信します。
試してみましょう。まず `html` ディレクトリを作って、`index.html` を置きます。 試してみましょう。まず`html`ディレクトリを作って、`index.html`を置きます。
```sh ```sh
mkdir html mkdir html
@@ -49,9 +49,9 @@ g++ -std=c++17 -o server server.cpp -pthread
./server ./server
``` ```
ブラウザで `http://localhost:8080` を開いてみてください。`html/index.html` の内容が表示されるはずです。`http://localhost:8080/index.html` でも同じページが返ります。 ブラウザで`http://localhost:8080`を開いてみてください。`html/index.html`の内容が表示されるはずです。`http://localhost:8080/index.html`でも同じページが返ります。
もちろん、前章のクライアントコードや `curl` でもアクセスできますよ。 もちろん、前章のクライアントコードや`curl`でもアクセスできますよ。
```cpp ```cpp
httplib::Client cli("http://localhost:8080"); httplib::Client cli("http://localhost:8080");
@@ -67,7 +67,7 @@ curl http://localhost:8080
## 複数のマウントポイント ## 複数のマウントポイント
`set_mount_point()` は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。 `set_mount_point()`は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。
```cpp ```cpp
svr.set_mount_point("/", "./public"); svr.set_mount_point("/", "./public");
@@ -75,7 +75,7 @@ svr.set_mount_point("/assets", "./static/assets");
svr.set_mount_point("/docs", "./documentation"); svr.set_mount_point("/docs", "./documentation");
``` ```
`/assets/style.css` なら `./static/assets/style.css` を、`/docs/guide.html` なら `./documentation/guide.html` を配信します。 `/assets/style.css`なら`./static/assets/style.css`を、`/docs/guide.html`なら`./documentation/guide.html`を配信します。
## ハンドラーとの組み合わせ ## ハンドラーとの組み合わせ
@@ -95,11 +95,11 @@ svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080); svr.listen("0.0.0.0", 8080);
``` ```
ハンドラーが先に評価されます。`/api/hello` にはハンドラーが応答し、それ以外のパスは `./public` ディレクトリからファイルを探します。 リクエストが来ると、まず`./public`ディレクトリからファイルを探し、見つからなければハンドラーを呼びます。`./public/api/hello`というファイルを置かない限り、`/api/hello`にはハンドラーが応答します。
## レスポンスヘッダーの追加 ## レスポンスヘッダーの追加
`set_mount_point()` の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。 `set_mount_point()`の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。
```cpp ```cpp
svr.set_mount_point("/", "./public", { svr.set_mount_point("/", "./public", {
@@ -111,7 +111,7 @@ svr.set_mount_point("/", "./public", {
## 静的ファイルサーバー用のDockerファイル ## 静的ファイルサーバー用のDockerファイル
cpp-httplibのリポジトリには、静的ファイルサーバー用の `Dockerfile` が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。 cpp-httplibのリポジトリには、静的ファイルサーバー用の`Dockerfile`が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。
```sh ```sh
> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server > docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
@@ -123,7 +123,7 @@ Press Ctrl+C to shutdown gracefully...
192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..." 192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
``` ```
`./my-site` ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。 `./my-site`ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。
## 次のステップ ## 次のステップ
+3 -3
View File
@@ -19,7 +19,7 @@ order: 5
## コンパイルオプション ## コンパイルオプション
TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT` マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。 TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT`マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。
```sh ```sh
# macOS (Homebrew) # macOS (Homebrew)
@@ -48,7 +48,7 @@ cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto
## 動作確認 ## 動作確認
ちゃんと動くか確認してみましょう。`httplib::Client` にHTTPSのURLを渡してアクセスするだけのプログラムです。 ちゃんと動くか確認してみましょう。`httplib::Client`にHTTPSのURLを渡してアクセスするだけのプログラムです。
```cpp ```cpp
#define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
@@ -67,7 +67,7 @@ int main() {
} }
``` ```
コンパイルして実行してみてください。`Status: 200` と表示されれば、セットアップ完了です。 コンパイルして実行してみてください。`Status: 200`と表示されれば、セットアップ完了です。
## 他のTLSバックエンド ## 他のTLSバックエンド
+7 -7
View File
@@ -3,7 +3,7 @@ title: "HTTPS Client"
order: 6 order: 6
--- ---
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った `httplib::Client` がそのまま使えます。コンストラクタに `https://` 付きのURLを渡すだけです。 前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った`httplib::Client`がそのまま使えます。コンストラクタに`https://`付きのURLを渡すだけです。
## GETリクエスト ## GETリクエスト
@@ -27,7 +27,7 @@ int main() {
} }
``` ```
2章では `httplib::Client cli("http://localhost:8080")` と書きましたよね。スキームを `https://` に変えるだけです。`Get()` や `Post()` など、2章で学んだAPIはすべてそのまま使えます。 2章では`httplib::Client cli("http://localhost:8080")`と書きましたよね。スキームを`https://`に変えるだけです。`Get()`や`Post()`など、2章で学んだAPIはすべてそのまま使えます。
```sh ```sh
curl https://nghttp2.org/ curl https://nghttp2.org/
@@ -43,13 +43,13 @@ httplib::Client cli("https://localhost:8443");
## CA証明書の検証 ## CA証明書の検証
`httplib::Client` はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。 `httplib::Client`はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。 CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。
### CA証明書ファイルの指定 ### CA証明書ファイルの指定
環境によってはシステムのCA証明書が見つからないこともあります。そのときは `set_ca_cert_path()` でパスを直接指定してください。 環境によってはシステムのCA証明書が見つからないこともあります。そのときは`set_ca_cert_path()`でパスを直接指定してください。
```cpp ```cpp
httplib::Client cli("https://nghttp2.org"); httplib::Client cli("https://nghttp2.org");
@@ -81,9 +81,9 @@ curl -k https://localhost:8443/
## リダイレクトの追跡 ## リダイレクトの追跡
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば `http://` から `https://` へ、あるいは `www` なしから `www` ありへ転送されるケースです。 HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば`http://`から`https://`へ、あるいは`www`なしから`www`ありへ転送されるケースです。
デフォルトではリダイレクトを追跡しません。リダイレクト先は `Location` ヘッダーで確認できます。 デフォルトではリダイレクトを追跡しません。リダイレクト先は`Location`ヘッダーで確認できます。
```cpp ```cpp
httplib::Client cli("https://nghttp2.org"); httplib::Client cli("https://nghttp2.org");
@@ -99,7 +99,7 @@ if (res) {
curl https://nghttp2.org/httpbin/redirect/3 curl https://nghttp2.org/httpbin/redirect/3
``` ```
`set_follow_location(true)` を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。 `set_follow_location(true)`を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
```cpp ```cpp
httplib::Client cli("https://nghttp2.org"); httplib::Client cli("https://nghttp2.org");
+8 -8
View File
@@ -3,7 +3,7 @@ title: "HTTPS Server"
order: 7 order: 7
--- ---
前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の `httplib::Server` を `httplib::SSLServer` に置き換えるだけです。 前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の`httplib::Server`を`httplib::SSLServer`に置き換えるだけです。
ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。 ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。
@@ -41,24 +41,24 @@ int main() {
} }
``` ```
`httplib::SSLServer` のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の `httplib::Server` とまったく同じですよ。 `httplib::SSLServer`のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の`httplib::Server`とまったく同じですよ。
コンパイルして起動しましょう。 コンパイルして起動しましょう。
## 動作確認 ## 動作確認
サーバーが起動したら、`curl` でアクセスしてみましょう。自己署名証明書なので、`-k` オプションで証明書検証をスキップします。 サーバーが起動したら、`curl`でアクセスしてみましょう。自己署名証明書なので、`-k`オプションで証明書検証をスキップします。
```sh ```sh
curl -k https://localhost:8443/ curl -k https://localhost:8443/
# Hello, HTTPS! # Hello, HTTPS!
``` ```
ブラウザで `https://localhost:8443` を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。 ブラウザで`https://localhost:8443`を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。
## クライアントからの接続 ## クライアントからの接続
前章の `httplib::Client` で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。 前章の`httplib::Client`で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。
### 方法1: 証明書検証を無効にする ### 方法1: 証明書検証を無効にする
@@ -82,7 +82,7 @@ int main() {
### 方法2: 自己署名証明書をCA証明書として指定する ### 方法2: 自己署名証明書をCA証明書として指定する
こちらのほうが安全です。`cert.pem` をCA証明書として信頼するよう指定します。 こちらのほうが安全です。`cert.pem`をCA証明書として信頼するよう指定します。
```cpp ```cpp
#define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
@@ -102,9 +102,9 @@ int main() {
この方法なら、指定した証明書のサーバーにだけ接続を許可して、なりすましを防げます。テスト環境でもなるべくこちらを使いましょう。 この方法なら、指定した証明書のサーバーにだけ接続を許可して、なりすましを防げます。テスト環境でもなるべくこちらを使いましょう。
## Server と SSLServer の比較 ## ServerとSSLServerの比較
3章で学んだ `httplib::Server` のAPIは、`httplib::SSLServer` でもそのまま使えます。違いはコンストラクタだけです。 3章で学んだ`httplib::Server`のAPIは、`httplib::SSLServer`でもそのまま使えます。違いはコンストラクタだけです。
| | `httplib::Server` | `httplib::SSLServer` | | | `httplib::Server` | `httplib::SSLServer` |
| -- | ------------------ | -------------------- | | -- | ------------------ | -------------------- |
+11 -9
View File
@@ -30,13 +30,13 @@ int main() {
} }
``` ```
`svr.WebSocket()` でWebSocketハンドラーを登録します。3章の `svr.Get()` や `svr.Post()` と同じ感覚ですね。 `svr.WebSocket()`でWebSocketハンドラーを登録します。3章の`svr.Get()`や`svr.Post()`と同じ感覚ですね。
ハンドラーの中では、`ws.read(msg)` でメッセージを待ちます。接続が閉じられると `read()` が `false` を返すので、ループを抜けます。`ws.send(msg)` でメッセージを送り返します。 ハンドラーの中では、`ws.read(msg)`でメッセージを待ちます。接続が閉じられると`read()`が`false`を返すので、ループを抜けます。`ws.send(msg)`でメッセージを送り返します。
## クライアントからの接続 ## クライアントからの接続
`httplib::ws::WebSocketClient` を使ってサーバーに接続してみましょう。 `httplib::ws::WebSocketClient`を使ってサーバーに接続してみましょう。
```cpp ```cpp
#include "httplib.h" #include "httplib.h"
@@ -63,11 +63,11 @@ int main() {
} }
``` ```
コンストラクタには `ws://host:port/path` 形式のURLを渡します。`connect()` で接続を開始し、`send()` と `read()` でメッセージをやり取りします。 コンストラクタには`ws://host:port/path`形式のURLを渡します。`connect()`で接続を開始し、`send()`と`read()`でメッセージをやり取りします。
## テキストとバイナリ ## テキストとバイナリ
WebSocketにはテキストとバイナリの2種類のメッセージがあります。`read()` の戻り値で区別できます。 WebSocketにはテキストとバイナリの2種類のメッセージがあります。`read()`の戻り値で区別できます。
```cpp ```cpp
svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) { svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
@@ -90,7 +90,7 @@ svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
## リクエスト情報へのアクセス ## リクエスト情報へのアクセス
ハンドラーの第1引数 `req` から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。 ハンドラーの第1引数`req`から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。
```cpp ```cpp
svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) { svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
@@ -107,9 +107,11 @@ svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws)
}); });
``` ```
ハンドラー内のチェックは、ハンドシェイクが完了した後に行われます。アップグレードする前に401などのHTTPステータスで接続を拒否したい場合は、`set_pre_request_handler()`を使ってください。WebSocketのルートでも呼ばれます。詳しくは[S11. Pre-request handlerでルート単位の認証を行う](../../cookbook/s11-pre-request)を参照してください。
## WSSで使う ## WSSで使う
HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は `httplib::SSLServer` にWebSocketハンドラーを登録するだけです。 HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は`httplib::SSLServer`にWebSocketハンドラーを登録するだけです。
```cpp ```cpp
httplib::SSLServer svr("cert.pem", "key.pem"); httplib::SSLServer svr("cert.pem", "key.pem");
@@ -124,7 +126,7 @@ svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
svr.listen("0.0.0.0", 8443); svr.listen("0.0.0.0", 8443);
``` ```
クライアント側は `wss://` スキームを使います。 クライアント側は`wss://`スキームを使います。
```cpp ```cpp
httplib::ws::WebSocketClient client("wss://localhost:8443/ws"); httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
@@ -132,7 +134,7 @@ httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
## 次のステップ ## 次のステップ
WebSocketの基本がわかりましたね。ここまでで Tourは終わりです。 WebSocketの基本がわかりましたね。ここまででTourは終わりです。
次のページでは、Tourで取り上げなかった機能をまとめて紹介します。 次のページでは、Tourで取り上げなかった機能をまとめて紹介します。
+10 -10
View File
@@ -7,7 +7,7 @@ Tourお疲れさまでした! cpp-httplibの基本はひと通り押さえま
## Streaming API ## Streaming API
LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()` を使えば、データをチャンクごとに処理できます。 LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()`を使えば、データをチャンクごとに処理できます。
```cpp ```cpp
httplib::Client cli("http://localhost:11434"); httplib::Client cli("http://localhost:11434");
@@ -21,7 +21,7 @@ if (result) {
} }
``` ```
`Get()` に `content_receiver` コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。 `Get()`に`content_receiver`コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。
```cpp ```cpp
httplib::Client cli("http://localhost:8080"); httplib::Client cli("http://localhost:8080");
@@ -32,7 +32,7 @@ cli.Get("/stream", [](const char *data, size_t len) {
}); });
``` ```
サーバー側には `set_content_provider()` と `set_chunked_content_provider()` があります。サイズがわかっているなら前者、不明なら後者を使ってください。 サーバー側には`set_content_provider()`と`set_chunked_content_provider()`があります。サイズがわかっているなら前者、不明なら後者を使ってください。
```cpp ```cpp
// サイズ指定あり(Content-Length が設定される) // サイズ指定あり(Content-Length が設定される)
@@ -50,12 +50,12 @@ svr.Get("/stream", [](const auto &, auto &res) {
res.set_chunked_content_provider("text/plain", res.set_chunked_content_provider("text/plain",
[](size_t offset, httplib::DataSink &sink) { [](size_t offset, httplib::DataSink &sink) {
sink.write("chunk\n", 6); sink.write("chunk\n", 6);
return true; // falseを返すと終了 return true; // 終了するときはsink.done()を呼ぶ
}); });
}); });
``` ```
大きなファイルのアップロードには `make_file_provider()` が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。 大きなファイルのアップロードには`make_file_provider()`が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。
```cpp ```cpp
httplib::Client cli("http://localhost:8080"); httplib::Client cli("http://localhost:8080");
@@ -67,7 +67,7 @@ auto res = cli.Post("/upload", {}, {}, {
## Server-Sent Events (SSE) ## Server-Sent Events (SSE)
SSEクライアントも用意しています。自動再接続や `Last-Event-ID` による再開にも対応しています。 SSEクライアントも用意しています。自動再接続や`Last-Event-ID`による再開にも対応しています。
```cpp ```cpp
httplib::Client cli("http://localhost:8080"); httplib::Client cli("http://localhost:8080");
@@ -155,12 +155,12 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
}); });
svr.set_post_routing_handler([](const auto &req, auto &res) { svr.set_post_routing_handler([](const auto &req, auto &res) {
// レスポンスが返された後に実行される // レスポンスを送信する直前に実行される
res.set_header("X-Server", "cpp-httplib"); res.set_header("X-Server", "cpp-httplib");
}); });
``` ```
`res.user_data` を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。 `res.user_data`を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。
```cpp ```cpp
svr.set_pre_routing_handler([](const auto &req, auto &res) { svr.set_pre_routing_handler([](const auto &req, auto &res) {
@@ -168,7 +168,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled; 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"); auto *user = res.user_data.get<std::string>("auth_user");
res.set_content("Hello, " + *user, "text/plain"); res.set_content("Hello, " + *user, "text/plain");
}); });
@@ -205,7 +205,7 @@ TCP以外に、Unix Domain Socketでの通信にも対応しています。同
// サーバー // サーバー
httplib::Server svr; httplib::Server svr;
svr.set_address_family(AF_UNIX); svr.set_address_family(AF_UNIX);
svr.listen("/tmp/httplib.sock", 0); svr.listen("/tmp/httplib.sock", 80); // ポート番号は使われない(0以外を渡す)
``` ```
```cpp ```cpp
+2 -2
View File
@@ -5,11 +5,11 @@ order: 0
cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。 cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。
1. [Getting Started](01-getting-started) — httplib.h の入手とHello Worldサーバー 1. [Getting Started](01-getting-started) — httplib.hの入手とHello Worldサーバー
2. [Basic Client](02-basic-client) — GET/POST・パスパラメーターのリクエスト送信 2. [Basic Client](02-basic-client) — GET/POST・パスパラメーターのリクエスト送信
3. [Basic Server](03-basic-server) — ルーティング、パスパラメーター、レスポンスの組み立て 3. [Basic Server](03-basic-server) — ルーティング、パスパラメーター、レスポンスの組み立て
4. [Static File Server](04-static-file-server) — 静的ファイルの配信 4. [Static File Server](04-static-file-server) — 静的ファイルの配信
5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLS のセットアップ 5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLSのセットアップ
6. [HTTPS Client](06-https-client) — HTTPSサイトへのリクエスト 6. [HTTPS Client](06-https-client) — HTTPSサイトへのリクエスト
7. [HTTPS Server](07-https-server) — HTTPSサーバーの構築 7. [HTTPS Server](07-https-server) — HTTPSサーバーの構築
8. [WebSocket](08-websocket) — WebSocket通信の基本 8. [WebSocket](08-websocket) — WebSocket通信の基本
+1013 -383
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -164,14 +164,18 @@ if [ "$DRY_RUN" -eq 1 ]; then
echo "==> Dry run complete. No changes were made." echo "==> Dry run complete. No changes were made."
else else
echo "==> Updating httplib.h..." echo "==> Updating httplib.h..."
sed -i '' "s/#define CPPHTTPLIB_VERSION \"[^\"]*\"/#define CPPHTTPLIB_VERSION \"$NEW_VERSION\"/" httplib.h # `-i.bak` is the in-place form GNU and BSD sed both accept (`-i ''` is
sed -i '' "s/#define CPPHTTPLIB_VERSION_NUM \"0x[0-9a-fA-F]*\"/#define CPPHTTPLIB_VERSION_NUM \"$VERSION_HEX\"/" httplib.h # BSD-only: GNU sed reads the '' as the script).
sed -i.bak "s/#define CPPHTTPLIB_VERSION \"[^\"]*\"/#define CPPHTTPLIB_VERSION \"$NEW_VERSION\"/" httplib.h
sed -i.bak "s/#define CPPHTTPLIB_VERSION_NUM \"0x[0-9a-fA-F]*\"/#define CPPHTTPLIB_VERSION_NUM \"$VERSION_HEX\"/" httplib.h
rm -f httplib.h.bak
echo " CPPHTTPLIB_VERSION = \"$NEW_VERSION\"" echo " CPPHTTPLIB_VERSION = \"$NEW_VERSION\""
echo " CPPHTTPLIB_VERSION_NUM = \"$VERSION_HEX\"" echo " CPPHTTPLIB_VERSION_NUM = \"$VERSION_HEX\""
echo "" echo ""
echo "==> Updating docs-src/config.toml..." echo "==> Updating docs-src/config.toml..."
sed -i '' "s/^version = \"[^\"]*\"/version = \"$NEW_VERSION\"/" docs-src/config.toml sed -i.bak "s/^version = \"[^\"]*\"/version = \"$NEW_VERSION\"/" docs-src/config.toml
rm -f docs-src/config.toml.bak
echo " version = \"$NEW_VERSION\"" echo " version = \"$NEW_VERSION\""
# --- Step 6: Commit, tag, and push --- # --- Step 6: Commit, tag, and push ---
+16
View File
@@ -146,6 +146,22 @@ if(HTTPLIB_IS_USING_OPENSSL)
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND_ERROR_IS_FATAL ANY COMMAND_ERROR_IS_FATAL ANY
) )
# cert_san_types.pem: the bytes of each SAN read as the other type:
# DNS:a.zz is 97.46.122.122, IP:42.46.122.122 is "*.zz".
execute_process(
COMMAND ${OPENSSL_COMMAND} req -x509 -key key.pem -sha256 -days 3650 -nodes -subj /CN=san-types -addext subjectAltName=DNS:a.zz,IP:42.46.122.122 -out cert_san_types.pem
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND_ERROR_IS_FATAL ANY
)
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not
# leftmost. "*.leftmost.example.test" matches a single
# label; the wildcard in "www.*.example.test" must not be
# honoured.
execute_process(
COMMAND ${OPENSSL_COMMAND} req -x509 -key key.pem -sha256 -days 3650 -nodes -subj /CN=wildcard-san -addext subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test -out cert_wildcard_san.pem
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND_ERROR_IS_FATAL ANY
)
endif() endif()
add_subdirectory(fuzzing) add_subdirectory(fuzzing)
+1 -1
View File
@@ -1,5 +1,5 @@
CXX = clang++ CXX = clang++
CXXFLAGS = -g -std=c++11 -I. -Wall -Wextra -Wtype-limits -Wconversion -Wshadow $(EXTRA_CXXFLAGS) -DCPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO -fsanitize=address # -fno-exceptions -DCPPHTTPLIB_NO_EXCEPTIONS CXXFLAGS = -g -std=c++11 -I. -Wall -Wextra -Wtype-limits -Wconversion -Wshadow -DCPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO -fsanitize=address $(EXTRA_CXXFLAGS) # -fno-exceptions -DCPPHTTPLIB_NO_EXCEPTIONS
ifneq ($(OS), Windows_NT) ifneq ($(OS), Windows_NT)
UNAME_S := $(shell uname -s) UNAME_S := $(shell uname -s)
+9
View File
@@ -33,3 +33,12 @@ openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=127.0.0.1" -
# different address. The SAN address must match; the CN address # different address. The SAN address must match; the CN address
# must be ignored. # must be ignored.
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=::1" -addext "subjectAltName=IP:2001:db8::1" -out cert_ipv6.pem openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=::1" -addext "subjectAltName=IP:2001:db8::1" -out cert_ipv6.pem
# cert_san_types.pem: the bytes of each SAN read as the other type:
# DNS:a.zz is 97.46.122.122, IP:42.46.122.122 is "*.zz".
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=san-types" -addext "subjectAltName=DNS:a.zz,IP:42.46.122.122" -out cert_san_types.pem
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not leftmost.
# "*.leftmost.example.test" matches a single label; the
# wildcard in "www.*.example.test" must not be honoured.
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=wildcard-san" -addext "subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test" -out cert_wildcard_san.pem
+22 -1
View File
@@ -137,6 +137,25 @@ cert_ipv6_pem = custom_target(
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=::1', '-addext', 'subjectAltName=IP:2001:db8::1', '-out', '@OUTPUT@'] command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=::1', '-addext', 'subjectAltName=IP:2001:db8::1', '-out', '@OUTPUT@']
) )
# cert_san_types.pem: the bytes of each SAN read as the other type: DNS:a.zz is
# 97.46.122.122, IP:42.46.122.122 is "*.zz".
cert_san_types_pem = custom_target(
'cert_san_types_pem',
input: key_pem,
output: 'cert_san_types.pem',
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=san-types', '-addext', 'subjectAltName=DNS:a.zz,IP:42.46.122.122', '-out', '@OUTPUT@']
)
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not leftmost.
# "*.leftmost.example.test" matches a single label; the wildcard in
# "www.*.example.test" must not be honoured.
cert_wildcard_san_pem = custom_target(
'cert_wildcard_san_pem',
input: key_pem,
output: 'cert_wildcard_san.pem',
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=wildcard-san', '-addext', 'subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test', '-out', '@OUTPUT@']
)
# Copy test files to the build directory # Copy test files to the build directory
configure_file(input: 'ca-bundle.crt', output: 'ca-bundle.crt', copy: true) configure_file(input: 'ca-bundle.crt', output: 'ca-bundle.crt', copy: true)
configure_file(input: 'image.jpg', output: 'image.jpg', copy: true) configure_file(input: 'image.jpg', output: 'image.jpg', copy: true)
@@ -178,7 +197,9 @@ test(
client_encrypted_pbes1_key_pem, client_encrypted_pbes1_key_pem,
client_encrypted_cert_pem, client_encrypted_cert_pem,
cert_ip_cn_pem, cert_ip_cn_pem,
cert_ipv6_pem cert_ipv6_pem,
cert_san_types_pem,
cert_wildcard_san_pem
], ],
workdir: meson.current_build_dir(), workdir: meson.current_build_dir(),
timeout: 300 timeout: 300
+21
View File
@@ -18,3 +18,24 @@ services:
context: ./ context: ./
args: args:
auth: digest auth: digest
# Self-hosted stand-in for the httpbin.org-style auth-testing endpoints
# (/basic-auth, /digest-auth) that BaseAuthTest/DigestAuthTest exercise
# through the proxies above, so those tests don't depend on an external
# site's uptime.
httpbin_backend:
image: mccutchen/go-httpbin:latest
restart: always
# TLS termination in front of httpbin_backend (which only speaks plain
# HTTP) so the SSL variants of those tests can CONNECT-tunnel through the
# proxies to "httpbin" on port 443, same as the NoSSL variants do on 80.
httpbin:
image: nginx:alpine
restart: always
depends_on:
- httpbin_backend
volumes:
- ./httpbin_nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ../cert.pem:/etc/nginx/certs/cert.pem:ro
- ../key.pem:/etc/nginx/certs/key.pem:ro
+22
View File
@@ -0,0 +1,22 @@
server {
listen 80;
server_name httpbin;
location / {
proxy_pass http://httpbin_backend:8080;
proxy_set_header Host $host;
}
}
server {
listen 443 ssl;
server_name httpbin;
ssl_certificate /etc/nginx/certs/cert.pem;
ssl_certificate_key /etc/nginx/certs/key.pem;
location / {
proxy_pass http://httpbin_backend:8080;
proxy_set_header Host $host;
}
}
+2655 -297
View File
File diff suppressed because it is too large. Load diff
+36 -25
View File
@@ -22,23 +22,25 @@ template <typename T> void ProxyTest(T &cli, bool basic) {
} }
TEST(ProxyTest, NoSSLBasic) { TEST(ProxyTest, NoSSLBasic) {
Client cli("httpbingo.org"); Client cli("httpbin");
ProxyTest(cli, true); ProxyTest(cli, true);
} }
#ifdef CPPHTTPLIB_SSL_ENABLED #ifdef CPPHTTPLIB_SSL_ENABLED
TEST(ProxyTest, SSLBasic) { TEST(ProxyTest, SSLBasic) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
ProxyTest(cli, true); ProxyTest(cli, true);
} }
TEST(ProxyTest, NoSSLDigest) { TEST(ProxyTest, NoSSLDigest) {
Client cli("httpbingo.org"); Client cli("httpbin");
ProxyTest(cli, false); ProxyTest(cli, false);
} }
TEST(ProxyTest, SSLDigest) { TEST(ProxyTest, SSLDigest) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
ProxyTest(cli, false); ProxyTest(cli, false);
} }
#endif #endif
@@ -63,23 +65,25 @@ void RedirectProxyText(T &cli, const char *path, bool basic) {
} }
TEST(RedirectTest, HTTPBinNoSSLBasic) { TEST(RedirectTest, HTTPBinNoSSLBasic) {
Client cli("httpbingo.org"); Client cli("httpbin");
RedirectProxyText(cli, "/redirect/2", true); RedirectProxyText(cli, "/redirect/2", true);
} }
#ifdef CPPHTTPLIB_SSL_ENABLED #ifdef CPPHTTPLIB_SSL_ENABLED
TEST(RedirectTest, HTTPBinNoSSLDigest) { TEST(RedirectTest, HTTPBinNoSSLDigest) {
Client cli("httpbingo.org"); Client cli("httpbin");
RedirectProxyText(cli, "/redirect/2", false); RedirectProxyText(cli, "/redirect/2", false);
} }
TEST(RedirectTest, HTTPBinSSLBasic) { TEST(RedirectTest, HTTPBinSSLBasic) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
RedirectProxyText(cli, "/redirect/2", true); RedirectProxyText(cli, "/redirect/2", true);
} }
TEST(RedirectTest, HTTPBinSSLDigest) { TEST(RedirectTest, HTTPBinSSLDigest) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
RedirectProxyText(cli, "/redirect/2", false); RedirectProxyText(cli, "/redirect/2", false);
} }
#endif #endif
@@ -173,7 +177,8 @@ template <typename T> void BaseAuthTestFromHTTPWatch(T &cli) {
cli.Get("/basic-auth/hello/world", cli.Get("/basic-auth/hello/world",
Headers{make_basic_authentication_header("hello", "world")}); Headers{make_basic_authentication_header("hello", "world")});
ASSERT_TRUE(res != nullptr); ASSERT_TRUE(res != nullptr);
EXPECT_EQ(normalizeJson("{\"authenticated\":true,\"user\":\"hello\"}\n"), EXPECT_EQ(normalizeJson("{\"authenticated\":true,\"user\":\"hello\","
"\"authorized\":true}\n"),
normalizeJson(res->body)); normalizeJson(res->body));
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -182,7 +187,8 @@ template <typename T> void BaseAuthTestFromHTTPWatch(T &cli) {
cli.set_basic_auth("hello", "world"); cli.set_basic_auth("hello", "world");
auto res = cli.Get("/basic-auth/hello/world"); auto res = cli.Get("/basic-auth/hello/world");
ASSERT_TRUE(res != nullptr); ASSERT_TRUE(res != nullptr);
EXPECT_EQ(normalizeJson("{\"authenticated\":true,\"user\":\"hello\"}\n"), EXPECT_EQ(normalizeJson("{\"authenticated\":true,\"user\":\"hello\","
"\"authorized\":true}\n"),
normalizeJson(res->body)); normalizeJson(res->body));
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -203,13 +209,14 @@ template <typename T> void BaseAuthTestFromHTTPWatch(T &cli) {
} }
TEST(BaseAuthTest, NoSSL) { TEST(BaseAuthTest, NoSSL) {
Client cli("httpcan.org"); Client cli("httpbin");
BaseAuthTestFromHTTPWatch(cli); BaseAuthTestFromHTTPWatch(cli);
} }
#ifdef CPPHTTPLIB_SSL_ENABLED #ifdef CPPHTTPLIB_SSL_ENABLED
TEST(BaseAuthTest, SSL) { TEST(BaseAuthTest, SSL) {
SSLClient cli("httpcan.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
BaseAuthTestFromHTTPWatch(cli); BaseAuthTestFromHTTPWatch(cli);
} }
#endif #endif
@@ -228,21 +235,21 @@ template <typename T> void DigestAuthTestFromHTTPWatch(T &cli) {
} }
{ {
// go-httpbin (the "httpbin" test double) only implements MD5 and
// SHA-256 for digest auth, so SHA-256 is as far as this can exercise
// the client's digest-auth algorithm selection end-to-end.
std::vector<std::string> paths = { std::vector<std::string> paths = {
"/digest-auth/auth/hello/world/MD5", "/digest-auth/auth/hello/world/MD5",
"/digest-auth/auth/hello/world/SHA-256", "/digest-auth/auth/hello/world/SHA-256",
"/digest-auth/auth/hello/world/SHA-512",
}; };
cli.set_digest_auth("hello", "world"); cli.set_digest_auth("hello", "world");
for (auto path : paths) { for (auto path : paths) {
auto res = cli.Get(path.c_str()); auto res = cli.Get(path.c_str());
ASSERT_TRUE(res != nullptr); ASSERT_TRUE(res != nullptr);
std::string algo(path.substr(path.rfind('/') + 1)); EXPECT_EQ(normalizeJson("{\"authenticated\":true,\"user\":\"hello\","
EXPECT_EQ( "\"authorized\":true}\n"),
normalizeJson("{\"algorithm\":\"" + algo + normalizeJson(res->body));
"\",\"authenticated\":true,\"user\":\"hello\"}\n"),
normalizeJson(res->body));
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -263,12 +270,13 @@ template <typename T> void DigestAuthTestFromHTTPWatch(T &cli) {
} }
TEST(DigestAuthTest, SSL) { TEST(DigestAuthTest, SSL) {
SSLClient cli("httpcan.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
DigestAuthTestFromHTTPWatch(cli); DigestAuthTestFromHTTPWatch(cli);
} }
TEST(DigestAuthTest, NoSSL) { TEST(DigestAuthTest, NoSSL) {
Client cli("httpcan.org"); Client cli("httpbin");
DigestAuthTestFromHTTPWatch(cli); DigestAuthTestFromHTTPWatch(cli);
} }
#endif #endif
@@ -329,22 +337,24 @@ template <typename T> void KeepAliveTest(T &cli, bool basic) {
#ifdef CPPHTTPLIB_SSL_ENABLED #ifdef CPPHTTPLIB_SSL_ENABLED
TEST(KeepAliveTest, NoSSLWithBasic) { TEST(KeepAliveTest, NoSSLWithBasic) {
Client cli("httpbingo.org"); Client cli("httpbin");
KeepAliveTest(cli, true); KeepAliveTest(cli, true);
} }
TEST(KeepAliveTest, SSLWithBasic) { TEST(KeepAliveTest, SSLWithBasic) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
KeepAliveTest(cli, true); KeepAliveTest(cli, true);
} }
TEST(KeepAliveTest, NoSSLWithDigest) { TEST(KeepAliveTest, NoSSLWithDigest) {
Client cli("httpbingo.org"); Client cli("httpbin");
KeepAliveTest(cli, false); KeepAliveTest(cli, false);
} }
TEST(KeepAliveTest, SSLWithDigest) { TEST(KeepAliveTest, SSLWithDigest) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
KeepAliveTest(cli, false); KeepAliveTest(cli, false);
} }
#endif #endif
@@ -353,7 +363,8 @@ TEST(KeepAliveTest, SSLWithDigest) {
#ifdef CPPHTTPLIB_SSL_ENABLED #ifdef CPPHTTPLIB_SSL_ENABLED
TEST(ProxyTest, SSLOpenStream) { TEST(ProxyTest, SSLOpenStream) {
SSLClient cli("httpbingo.org"); SSLClient cli("httpbin");
cli.enable_server_certificate_verification(false);
cli.set_proxy("localhost", 3128); cli.set_proxy("localhost", 3128);
cli.set_proxy_basic_auth("hello", "world"); cli.set_proxy_basic_auth("hello", "world");
+80 -5
View File
@@ -3,11 +3,14 @@
// without waiting 30 seconds. // without waiting 30 seconds.
#define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 1 #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 1
#define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 3 #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 3
#define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 3
#include <httplib.h> #include <httplib.h>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include <future>
using namespace httplib; using namespace httplib;
class WebSocketHeartbeatTest : public ::testing::Test { class WebSocketHeartbeatTest : public ::testing::Test {
@@ -176,18 +179,90 @@ protected:
TEST_F(WebSocketPongTimeoutTest, ClientDetectsNonResponsivePeer) { TEST_F(WebSocketPongTimeoutTest, ClientDetectsNonResponsivePeer) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws"); ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
client.set_websocket_max_missed_pongs(2); client.set_websocket_max_missed_pongs(2);
// A read timeout asked for at runtime is reported as Timeout, so it cannot
// be mistaken for the Fail a pong timeout produces.
client.set_read_timeout(10);
ASSERT_TRUE(client.connect()); ASSERT_TRUE(client.connect());
ASSERT_TRUE(client.is_open()); ASSERT_TRUE(client.is_open());
// Client pings every 1s (compile-time default in this test file). // Client pings every 1s (compile-time default in this test file).
// With max_missed_pongs = 2, the heartbeat thread should self-close within // With max_missed_pongs = 2, the heartbeat thread should self-close within
// roughly 3s. Poll is_open() up to 6s. // roughly 3s, and that has to end a read() already waiting on the peer.
auto start = std::chrono::steady_clock::now(); auto start = std::chrono::steady_clock::now();
while (client.is_open() && std::string msg;
std::chrono::steady_clock::now() - start < std::chrono::seconds(6)) { EXPECT_EQ(client.read(msg), ws::Fail);
std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_TRUE(std::chrono::steady_clock::now() - start <
std::chrono::seconds(6));
EXPECT_FALSE(client.is_open());
}
// The compile-time client read timeout (3s here) was never asked for through
// set_read_timeout(), so when it elapses read() reports Fail and closes the
// connection rather than handing back a Timeout on a still-open one.
TEST_F(WebSocketPongTimeoutTest, CompileTimeClientReadTimeoutIsFail) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
client.set_websocket_ping_interval(0);
ASSERT_TRUE(client.connect());
// Server pings are off and its handler never sends, so nothing arrives.
std::string msg;
EXPECT_EQ(client.read(msg), ws::Fail);
EXPECT_FALSE(client.is_open());
}
// The compile-time server read timeout (3s here) is a backstop that reclaims
// the worker from a peer gone quiet, not a timeout the handler asked for. When
// it elapses read() must return Fail, so a handler written as
// `while (ws.read(msg))` ends instead of re-running its body with the previous
// message still in `msg`.
class WebSocketServerReadTimeoutTest : public ::testing::Test {
protected:
void SetUp() override {
svr_.set_websocket_ping_interval(0);
svr_.WebSocket("/ws", [this](const Request &, ws::WebSocket &ws) {
std::string msg;
while (ws.read(msg)) {
iterations_++;
ws.send(msg);
}
handler_done_.set_value();
});
port_ = svr_.bind_to_any_port("localhost");
thread_ = std::thread([this]() { svr_.listen_after_bind(); });
svr_.wait_until_ready();
} }
void TearDown() override {
svr_.stop();
thread_.join();
}
Server svr_;
int port_;
std::thread thread_;
std::atomic<int> iterations_{0};
std::promise<void> handler_done_;
};
TEST_F(WebSocketServerReadTimeoutTest, BackstopEndsHandlerLoop) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
client.set_websocket_ping_interval(0); // nothing reaches the server's read()
client.set_read_timeout(10, 0); // fail rather than hang
ASSERT_TRUE(client.connect());
ASSERT_TRUE(client.send("hello"));
std::string msg;
ASSERT_EQ(client.read(msg), ws::Text);
EXPECT_EQ("hello", msg);
// The client now stays silent. The server's backstop elapses and the
// handler returns, having run its loop body exactly once.
auto done = handler_done_.get_future();
ASSERT_EQ(done.wait_for(std::chrono::seconds(6)), std::future_status::ready);
EXPECT_EQ(1, iterations_.load());
EXPECT_EQ(client.read(msg), ws::Fail);
EXPECT_FALSE(client.is_open()); EXPECT_FALSE(client.is_open());
} }