Files
cpp-httplib/docs-src/pages/ja/cookbook/s08-compress-response.md
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

4.7 KiB
Raw Blame History

title, order, status
title order status
S08. レスポンスを圧縮して返す 27 draft

cpp-httplibは、クライアントがAccept-Encodingで対応を表明していれば、レスポンスボディを自動で圧縮してくれます。ハンドラ側で特別なことをする必要はありません。対応しているのはgzip、Brotli、Zstdです。

ビルド時の準備

圧縮機能を使うには、httplib.hをインクルードする前に対応するマクロを定義しておきます。

#define CPPHTTPLIB_ZLIB_SUPPORT     // gzip
#define CPPHTTPLIB_BROTLI_SUPPORT   // brotli
#define CPPHTTPLIB_ZSTD_SUPPORT     // zstd
#include <httplib.h>

それぞれzlib、brotli、zstdをリンクする必要があります。必要な圧縮方式だけ有効にすればOKです。

使い方

svr.Get("/api/data", [](const httplib::Request &req, httplib::Response &res) {
  std::string body = build_large_response();
  res.set_content(body, "application/json");
});

これだけです。クライアントがAccept-Encoding: gzipを送ってきていれば、cpp-httplibが自動でgzip圧縮して返します。レスポンスにはContent-Encoding: gzipとVary: Accept-Encodingが自動で付きます。

圧縮の優先順位

クライアントが複数の方式を受け入れる場合、Accept-Encodingのq値が最も高い方式が選ばれます。q値が同じなら、Brotli → gzip → Zstdの順です(ビルドで有効になっている中から)。

ストリーミングレスポンスも圧縮される

set_chunked_content_provider()で返すストリーミングレスポンスも、同じように自動で圧縮されます。

svr.Get("/events", [](const httplib::Request &req, httplib::Response &res) {
  res.set_chunked_content_provider(
    "text/plain",
    [](size_t offset, httplib::DataSink &sink) {
      // ...
    });
});

静的ファイルは明示的に有効にする

set_mount_point()やResponse::set_file_content()でファイルをそのまま返す場合、デフォルトでは圧縮されません。有効にするには次を呼びます。

svr.set_static_file_compression(true);

圧縮の対象になるのは一定のサイズ範囲に収まるファイルだけで、上下どちらの境界も変更できます。

svr.set_static_file_compression_min_length(512);
svr.set_static_file_compression_max_length(1024 * 1024);

下限のデフォルトは1400バイトです。1500バイトのMTUに収まるレスポンスは、小さくしたところで到達が速くなるわけではありません。さらに数バイトのファイルは、gzipのヘッダとトレーラがdeflateの削減分を上回るため、かえって大きくなって返ります。

上限のデフォルトは4MBで、こちらは理由が違います。リクエストのたびに圧縮が走り、圧縮後のバイト列はレスポンスを書き終えるまでメモリに載るため、ピーク時のコストが同時処理中のリクエスト数に比例するからです。つまり1リクエストあたりのコストを抑えるための値であって、大きいファイルは圧縮しても無駄だという意味ではありません。配信するファイルが分かっていてトラフィックがそれほど多くないなら、引き上げて構いません。

どちらの境界も0で無効にできます。コンパイル時のデフォルトはCPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTHとCPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTHで決まります。

圧縮してもContent-Lengthは付いたままなので、HEADはGETと同じサイズを返します。細かい挙動として、Rangeリクエストは非圧縮の表現から切り出して返し、ETagにはW/"...-gzip"のように使われた圧縮方式が入ります。

なおset_content_provider()で登録したコンテンツプロバイダは対象外です。圧縮器を通すと、内部バッファが埋まるまで書き込みが送出されず、ボディを少しずつ生成するプロバイダが止まってしまうためです。生成したボディを圧縮したい場合はset_chunked_content_provider()を使ってください。

Note: サイズ範囲が効くのは静的ファイルだけです。set_content()に渡したボディは、圧縮対象のMIMEタイプでクライアントが受け入れていれば、大きさによらず圧縮されます。数バイトのレスポンスはgzipのヘッダ分だけかえって大きくなるので、避けたい場合はハンドラ側で判断してください。

クライアント側の挙動はC15. 圧縮を有効にするを参照してください。