mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-19 11:19:36 +00:00
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.
2.5 KiB
2.5 KiB
title, order, status
| title | order | status |
|---|---|---|
| S03. パスパラメーターを使う | 22 | draft |
REST APIでよく使う/users/:idのような動的なパスは、パスパターンに:nameを書くだけで使えます。マッチした値はreq.path_paramsに入ります。
基本の使い方
svr.Get("/users/:id", [](const httplib::Request &req, httplib::Response &res) {
auto id = req.path_params.at("id");
res.set_content("user id: " + id, "text/plain");
});
/users/42にアクセスすると、req.path_params["id"]に"42"が入ります。path_paramsはstd::unordered_map<std::string, std::string>なので、at()で取り出します。
複数のパラメーター
パラメーターはいくつでも書けます。
svr.Get("/orgs/:org/repos/:repo", [](const httplib::Request &req, httplib::Response &res) {
auto org = req.path_params.at("org");
auto repo = req.path_params.at("repo");
res.set_content(org + "/" + repo, "text/plain");
});
/orgs/anthropic/repos/cpp-httplibのようなパスがマッチします。
正規表現パターン
もっと柔軟にマッチさせたいときは、std::regexベースのパターンも使えます。
svr.Get(R"(/users/(\d+))", [](const httplib::Request &req, httplib::Response &res) {
auto id = req.matches[1];
res.set_content("user id: " + std::string(id), "text/plain");
});
パターンに括弧を使うと、マッチした部分がreq.matchesに入ります。req.matches[0]はパス全体、req.matches[1]以降がキャプチャです。
正規表現のルートは、CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH(デフォルトは256)より長いパスには適用されず、マッチしなかったものとして扱われます。長い入力でstd::regexがスタックを使い果たさないための制限です。もっと長いパスを扱いたい場合は、このマクロに大きな値を定義してください。
どちらを使うか
- 単純なIDやスラッグなら
:nameでじゅうぶん。読みやすく、型が自明です - 数値のみ、UUIDのみといった形式をURLで絞りたいなら正規表現が便利
- 両方を混ぜると混乱するので、プロジェクト内ではどちらかに統一するのがおすすめです
Note: パスパラメーターは文字列として入ってくるので、整数として使いたい場合は
std::stoi()などで変換してください。変換失敗のハンドリングも忘れずに。