mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-28 21:08:28 +00:00
There was no way to refuse a connection before the server read a request from it, or before the TLS handshake on SSLServer. The earliest hook was the pre-routing handler, after the request head had been read. set_accept_handler() takes a callback that gets each accepted socket and returns whether to serve it. Both accept paths, with and without keep-alive parking, go through one function, admit_accepted_socket(), which sets the socket timeouts first, so that a handler reading from the socket cannot block forever. A refused or throwing handler closes the socket; an exception is reported as Error::UserCallbackException. Fix #2700
72 lines
3.4 KiB
Markdown
72 lines
3.4 KiB
Markdown
---
|
|
title: "S09. 全ルートに共通の前処理をする"
|
|
order: 28
|
|
status: "draft"
|
|
---
|
|
|
|
すべてのリクエストに対して共通の処理を走らせたいことがあります。認証チェック、ロギング、レート制限などです。こうした処理は`set_pre_routing_handler()`で登録します。
|
|
|
|
## 基本の使い方
|
|
|
|
```cpp
|
|
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`を返す: ここでレスポンスが完了したとみなし、以降の処理をスキップ
|
|
|
|
## 認証チェックに使う
|
|
|
|
全ルート共通の認証を一箇所でかけられます。
|
|
|
|
```cpp
|
|
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でルート単位の認証を行う](../s11-pre-request)のほうが適しています。
|
|
|
|
## 接続の段階で断る
|
|
|
|
接続元のアドレスで絞り込むだけなら、リクエストを読む前に断れます。`set_accept_handler()`は、接続を受け付けた直後、リクエストを読む前(`SSLServer`ならTLSハンドシェイクの前)に呼ばれます。`false`を返すと、その接続は何も読まずに閉じられます。
|
|
|
|
```cpp
|
|
svr.set_accept_handler([](socket_t sock) {
|
|
sockaddr_storage addr;
|
|
socklen_t len = sizeof(addr);
|
|
if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
|
|
return false;
|
|
}
|
|
return is_allowed(addr); // 自前の判定
|
|
});
|
|
```
|
|
|
|
このハンドラは接続を受け付けるスレッドで動くので、時間のかかる処理を入れると新しい接続がすべて待たされます。また、ソケットはサーバーが閉じるので、ハンドラの中では閉じないでください。
|
|
|
|
> **Note:** レスポンスを加工したいだけなら、`set_post_routing_handler()`のほうが適切です。[S10. Post-routing handlerでレスポンスヘッダーを追加する](../s10-post-routing)を参照してください。
|