Add Server::CustomRoute() for HTTP methods outside the built-in set (#2553)

* Add Server::CustomRoute() for HTTP methods outside the built-in set

parse_request_line validates the request method against a fixed whitelist and
rejects anything else with 400 before routing runs. That blocks WebDAV, where
PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK and UNLOCK are ordinary methods
defined by RFC 4918, and it blocks extension methods such as UPnP's SUBSCRIBE.
The need has been open since #847.

Registering a handler is now what makes the server accept a method:

    svr.CustomRoute("PROPFIND", "/dav/:id", handler);

Because custom methods go through the normal dispatch path, patterns work the
way they do for Get() and friends, and the request body is available in
req.body. Serving these methods through set_pre_routing_handler was never
enough: the body has not been read at that point, so PROPPATCH and LOCK, which
require one, could not be implemented at all.

A HandlerWithContentReader overload is available too. The content reader gate
in routing() also fires when a custom method carries no body, matching what
expect_content() does unconditionally for POST/PUT/PATCH/DELETE, so a body-less
PROPFIND (RFC 4918 treats one as allprop) reaches its handler instead of
falling through to 404.

Method names are validated as RFC 9110 tokens, and the ten built-in methods are
refused. Seven of them are dispatched by the if/else chain in routing() before
the custom tables are consulted, so a route registered for one could never
fire; CONNECT, TRACE and PRI carry protocol-level meaning this library does not
route. A refused registration makes is_valid() return false, so listen() fails
rather than starting a server holding a handler that would never run. This is
also why SSLServer::is_valid() now chains to Server::is_valid() instead of only
checking ctx_.

Servers that never call CustomRoute() keep the previous per-request cost: the
built-in method set is checked first and short-circuits, and the custom lookup
returns early on an empty map.

* Add cookbook recipe for custom HTTP methods

The CustomRoute() docs were a section inside S01, which pushed that page to 90
lines, the longest in the cookbook, and mixed a separate feature into a page
about registering GET/POST/PUT/DELETE handlers. Move the section into its own
recipe and give it room for the part that was missing: the OPTIONS handler
returning DAV: and Allow, which WebDAV clients probe for before anything else.
S01 goes back to 68 lines and keeps a pointer to the new page.

The recipe is titled after the API rather than after WebDAV, and says outright
that generating the 207 Multi-Status XML, interpreting Depth and managing locks
are the reader's job. Routing the method is all the library does.

S23 takes order 42, so the TLS, SSE and WebSocket recipes shift to 43-57. That
only moves the sort key. Filenames, the T01/E01/W01 labels, the published URLs
and every cross-reference are untouched.
This commit is contained in:
yhirose
2026-08-25 19:31:42 -04:00
committed by GitHub
parent af75a4160f
commit 254e576b50
39 changed files with 588 additions and 39 deletions

View File

@@ -1,6 +1,6 @@
---
title: "E01. SSEサーバーを実装する"
order: 47
order: 48
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "E02. SSEでイベント名を使い分ける"
order: 48
order: 49
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "E03. SSEの再接続を処理する"
order: 49
order: 50
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "E04. SSEをクライアントで受信する"
order: 50
order: 51
status: "draft"
---

View File

@@ -73,6 +73,9 @@ status: "draft"
- [S21. マルチスレッド数を設定する](s21-thread-pool)
- [S22. Unix domain socketで通信する](s22-unix-socket)
### プロトコル拡張
- [S23. カスタムHTTPメソッドを扱う](s23-custom-methods)
## TLS / セキュリティ
- [T01. OpenSSL・mbedTLS・wolfSSLの選択指針](t01-tls-backends)

View File

@@ -4,7 +4,7 @@ order: 20
status: "draft"
---
`httplib::Server`では、HTTPメソッドごとにハンドラを登録します。`Get()``Post()``Put()``Delete()`の各メソッドにパターンとラムダを渡すだけです。
`httplib::Server`では、HTTPメソッドごとにハンドラを登録します。`Get()``Post()``Put()``Delete()`の各メソッドにパターンとラムダを渡すだけです。WebDAVの`PROPFIND`のような組み込み以外のメソッドを扱いたいときは、`CustomRoute()`を使います。
## 基本の使い方
@@ -64,3 +64,5 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
> **Note:** `listen()`はブロックする関数です。別スレッドで動かしたいときは`std::thread`で包むか、ノンブロッキング起動が必要なら[S18. `listen_after_bind`で起動順序を制御する](../s18-listen-after-bind)を参照してください。
> パスパラメーター(`/users/:id`)を使いたい場合は[S03. パスパラメーターを使う](../s03-path-params)を参照してください。
> WebDAVの`PROPFIND`のような組み込み以外のメソッドは[S23. カスタムHTTPメソッドを扱う](../s23-custom-methods)を参照してください。

View File

@@ -0,0 +1,59 @@
---
title: "S23. カスタムHTTPメソッドを扱う"
order: 42
status: "draft"
---
サーバーは知らないHTTPメソッドを`400 Bad Request`で弾きます。RFC 4918のWebDAVメソッド`PROPFIND``PROPPATCH``MKCOL`などやUPnPの`SUBSCRIBE`のような拡張メソッドを受け付けたいときは、`CustomRoute()`でハンドラを登録してください。登録したことがそのまま「このメソッドを受け付ける」という意味になります。
## 基本の使い方
```cpp
svr.CustomRoute("PROPFIND", "/dav/:id",
[](const httplib::Request &req, httplib::Response &res) {
// リクエストボディも通常どおり読める
auto id = req.path_params.at("id");
res.status = httplib::StatusCode::MultiStatus_207;
res.set_content(build_multistatus(req.body), "application/xml");
});
```
パターンの書き方は`Get()`などと同じです。正規表現もパスパラメーターもそのまま使えます。
## OPTIONSで対応メソッドを知らせる
WebDAVクライアントは接続すると、まず`OPTIONS`でサーバーの能力を問い合わせます。cpp-httplibは`DAV:`ヘッダーも`Allow`ヘッダーも自動生成しないので、自分で返してください。ここを忘れると、`PROPFIND`が正しく動いてもクライアントに拒否されます。
```cpp
svr.Options("/dav/.*", [](const httplib::Request &req, httplib::Response &res) {
res.set_header("DAV", "1");
res.set_header("Allow", "OPTIONS, GET, HEAD, PROPFIND, PROPPATCH, MKCOL");
});
```
## ボディをストリーミングで受け取る
`Post()`などと同じく、Content Reader版のオーバーロードがあります。大きなXMLを一度にメモリへ載せたくないときに使ってください。
```cpp
svr.CustomRoute("REPORT", "/dav/.*",
[](const httplib::Request &req, httplib::Response &res,
const httplib::ContentReader &content_reader) {
content_reader([&](const char *data, size_t data_length) {
// 少しずつ処理する
return true;
});
res.status = httplib::StatusCode::MultiStatus_207;
});
```
## 覚えておくこと
- メソッド名はHTTPのトークンRFC 9110である必要があります。`listen()`より前に登録してください
- `GET``HEAD``POST``PUT``DELETE``CONNECT``OPTIONS``TRACE``PATCH``PRI`は登録できません。これらには専用のメソッドを使ってください
- 登録が拒否されると`is_valid()``false`になり、`listen()`が失敗します。呼ばれないハンドラを抱えたままサーバーが起動することはありません
- 静的ファイルの配信とWebSocketのアップグレードは`GET`/`HEAD`のままです
> **Note:** cpp-httplibが用意するのはメソッドのルーティングまでです。WebDAVを名乗るなら、`207 Multi-Status`のXML生成、`Depth`ヘッダーの解釈、ロックの管理は自分で実装することになります。プロトコルの本体はライブラリの外側です。
> ハンドラ登録の基本は[S01. GET / POST / PUT / DELETEハンドラを登録する](../s01-handlers)を参照してください。

View File

@@ -1,6 +1,6 @@
---
title: "T01. OpenSSL・mbedTLS・wolfSSLの選択指針"
order: 42
order: 43
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "T02. SSL証明書の検証を制御する"
order: 43
order: 44
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "T03. SSL/TLSサーバーを立ち上げる"
order: 44
order: 45
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "T04. mTLSを設定する"
order: 45
order: 46
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "T05. サーバー側でピア証明書を参照する"
order: 46
order: 47
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "W01. WebSocketエコーサーバークライアントを実装する"
order: 51
order: 52
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "W02. ハートビートを設定する"
order: 52
order: 53
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "W03. 接続クローズをハンドリングする"
order: 53
order: 54
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "W04. バイナリフレームを送受信する"
order: 54
order: 55
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "W05. wss接続でTLSを設定する"
order: 55
order: 56
status: "draft"
---

View File

@@ -1,6 +1,6 @@
---
title: "W06. タイムアウトを設定する"
order: 56
order: 57
status: "draft"
---