Files
cpp-httplib/docs-src/pages/ja/cookbook/s09-pre-routing.md
T
yhirose 9bfd2ddf1c Fix README and docs pages that no longer match the code
Bring the READMEs and the docs pages (en and ja) in line with the
current header:

- Fix the client sample that does not compile, the Transfer-Encoding
  statement for default headers, the verifier callback comment, the
  thread pool spawn rule, the sanitize_filename description, and the
  inverted Accept-Encoding sentence.
- Describe recent behaviour: TLS errors behind Read/Write failures,
  Host validation, Connection: close for a body without length,
  content_reader rules, refused CONNECT, WebSocketClient proxies,
  CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and
  the payload limit of the Stream API.
- Complete the API references of WebSocket, WebSocketClient and the
  stream:: helpers, and the SSE reconnect rules.
- Fix cookbook pages: keychain loading on every backend, received Close
  status, a multipart sample that trusted the client's file name, an
  echo sample that sent binary as text, SNI, pre-request handler scope,
  stop() with WebSocket handlers, and the thread pool notes.
- Restore the mutex in the LLM app's Chapter 5 code.
2026-10-18 10:13:57 -04:00

2.5 KiB

title, order, status
title order status
S09. 全ルートに共通の前処理をする 28 draft

すべてのリクエストに対して共通の処理を走らせたいことがあります。認証チェック、ロギング、レート制限などです。こうした処理はset_pre_routing_handler()で登録します。

基本の使い方

svr.set_pre_routing_handler(
  [](const httplib::Request &req, httplib::Response &res) {
    std::cout << req.method << " " << req.path << std::endl;
    return httplib::Server::HandlerResponse::Unhandled;
  });

Pre-routingハンドラは、ルーティングよりも前に呼ばれます。どのハンドラにもマッチしないリクエストも含めて、すべてのリクエストを捕まえられます。ただし、リクエストラインやヘッダーの解析中に拒否されたリクエスト(不正なリクエストの400、長すぎるURIの414、不正なRangeの416)には、このハンドラが呼ばれる前にサーバーが応答します。

戻り値のHandlerResponseがポイントです。

  • Unhandledを返す: 通常の処理を続行(ルーティングとハンドラ呼び出し)
  • Handledを返す: ここでレスポンスが完了したとみなし、以降の処理をスキップ

認証チェックに使う

全ルート共通の認証を一箇所でかけられます。

svr.set_pre_routing_handler(
  [](const httplib::Request &req, httplib::Response &res) {
    if (req.path.rfind("/public", 0) == 0) {
      return httplib::Server::HandlerResponse::Unhandled; // 認証不要
    }

    auto auth = req.get_header_value("Authorization");
    if (auth.empty()) {
      res.status = 401;
      res.set_content("unauthorized", "text/plain");
      return httplib::Server::HandlerResponse::Handled;
    }

    return httplib::Server::HandlerResponse::Unhandled;
  });

認証が通らなければHandledを返してその場で401を返し、通ればUnhandledを返して通常のルーティングに進ませます。

特定ルートだけに認証をかけたい場合

全ルート共通ではなく、ルート単位で認証を分けたいときは、S11. Pre-request handlerでルート単位の認証を行うのほうが適しています。

Note: レスポンスを加工したいだけなら、set_post_routing_handler()のほうが適切です。S10. Post-routing handlerでレスポンスヘッダーを追加するを参照してください。