title: "S03. パスパラメーターを使う" order: 22
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]以降がキャプチャです。
:nameでじゅうぶん。読みやすく、型が自明ですNote: パスパラメーターは文字列として入ってくるので、整数として使いたい場合は
std::stoi()などで変換してください。変換失敗のハンドリングも忘れずに。