mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-06-10 16:47:14 +00:00
Read request body after route matching and pre-request handler
Previously, for regular handlers the request body was read in routing() before the route was matched, so the pre-request handler always saw an already-read body. The ContentReader path, in contrast, ran the pre-request handler before the body was read. This inconsistency made it impossible to reject a request (e.g. failed per-route authentication via req.matched_route) without buffering a potentially large body. Move the read_content() call into dispatch_request(), after route matching and the pre-request handler, so both paths behave the same: route matching -> pre_request_handler -> body read -> handler. A request rejected by the pre-request handler no longer reads the body at all; the existing keep-alive drain logic still consumes any framed body afterwards. Note: code that referenced req.body or body-derived form fields inside the pre-request handler will now see an empty body. Inspect headers, path, query parameters, or matched_route instead. Also document the handler execution order in README and update the pre-request cookbook pages (en/ja).
This commit is contained in:
@@ -8,13 +8,15 @@ status: "draft"
|
||||
|
||||
## Pre-routingとの違い
|
||||
|
||||
| フック | 呼ばれるタイミング | ルート情報 |
|
||||
| --- | --- | --- |
|
||||
| `set_pre_routing_handler` | ルーティングの前 | 取得できない |
|
||||
| `set_pre_request_handler` | ルーティング後、ルートハンドラの直前 | `req.matched_route`で取得可能 |
|
||||
| フック | 呼ばれるタイミング | ルート情報 | リクエストボディ |
|
||||
| --- | --- | --- | --- |
|
||||
| `set_pre_routing_handler` | ルーティングの前 | 取得できない | まだ読まれていない |
|
||||
| `set_pre_request_handler` | ルーティング後、ルートハンドラの直前 | `req.matched_route`で取得可能 | まだ読まれていない |
|
||||
|
||||
Pre-requestハンドラなら、`req.matched_route`に「マッチしたパターン文字列」が入っているので、ルートに応じて処理を変えられます。
|
||||
|
||||
Pre-requestハンドラが呼ばれる時点ではボディがまだ読まれていないので、認証に失敗したリクエストなどを、(巨大かもしれない)ボディを読み込む前に拒否できます。その代わり、`req.body`やボディから解析されるフォームフィールドはこの時点では参照できません。ヘッダ・パス・クエリパラメータ・`req.matched_route`を使って判断してください。
|
||||
|
||||
## ルートごとに認証を切り替える
|
||||
|
||||
```cpp
|
||||
|
||||
Reference in New Issue
Block a user