From fc2b7be765983fbce8a3839bc3ff16b51c81b44b Mon Sep 17 00:00:00 2001 From: Alex Hultman Date: Thu, 25 Jan 2024 01:37:45 +0100 Subject: [PATCH] Fix deep parameter routes --- src/HttpRouter.h | 7 ++++++- tests/HttpRouter.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/HttpRouter.h b/src/HttpRouter.h index 34c2322..39ebb2e 100644 --- a/src/HttpRouter.h +++ b/src/HttpRouter.h @@ -286,7 +286,12 @@ public: /* Iterate over all segments */ setUrl(pattern); for (int i = 0; !getUrlSegment(i).second; i++) { - node = getNode(node, std::string(getUrlSegment(i).first), priority == HIGH_PRIORITY); + std::string strippedSegment(getUrlSegment(i).first); + if (strippedSegment.length() && strippedSegment[0] == ':') { + /* Parameter routes must be named only : */ + strippedSegment = ":"; + } + node = getNode(node, strippedSegment, priority == HIGH_PRIORITY); } /* Insert handler in order sorted by priority (most significant 1 byte) */ node->handlers.insert(std::upper_bound(node->handlers.begin(), node->handlers.end(), (uint32_t) (priority | handlers.size())), (uint32_t) (priority | handlers.size())); diff --git a/tests/HttpRouter.cpp b/tests/HttpRouter.cpp index 531746c..8bd3af3 100644 --- a/tests/HttpRouter.cpp +++ b/tests/HttpRouter.cpp @@ -46,6 +46,34 @@ void testMethodPriority() { assert(result == "PSAS"); } +void testDeepParameterRoutes() { + std::cout << "TestDeepParameterRoutes" << std::endl; + uWS::HttpRouter r; + std::string result; + + r.add({"GET"}, "/something/:id/sync", [&result](auto *h) { + result += "ETT"; + return false; + }); + + r.add({"GET"}, "/something/:somethingId/pin", [&result](auto *h) { + result += "TVÅ"; + return false; + }); + + r.add({"GET"}, "/something/:id/:attribute", [&result](auto *h) { + result += "TRE"; + return false; + }); + + assert(r.route("GET", "/something/1234/pin") == false); + assert(result == "TVÅTRE"); + + result.clear(); + assert(r.route("GET", "/something/1234/sync") == false); + assert(result == "ETTTRE"); +} + void testPatternPriority() { std::cout << "TestPatternPriority" << std::endl; uWS::HttpRouter r; @@ -402,6 +430,7 @@ void testPerformance() { } int main() { + testDeepParameterRoutes(); testPatternPriority(); testMethodPriority(); testUpgrade();