From adcd226524e650eb4a01d9e5eb509f40a526692d Mon Sep 17 00:00:00 2001 From: Abhishek Choudhary Date: Fri, 19 Jan 2024 14:27:22 +0545 Subject: [PATCH] fix: give more priority to longer routes --- lib/resty/radixtree.lua | 3 +++ t/parameter.t | 45 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/lib/resty/radixtree.lua b/lib/resty/radixtree.lua index 72f3d3e..f20e501 100644 --- a/lib/resty/radixtree.lua +++ b/lib/resty/radixtree.lua @@ -204,6 +204,9 @@ local mt = { __index = _M, __gc = gc_free } local function sort_route(route_a, route_b) + if route_a.priority == route_b.priority then + return #route_a.path_org > #route_b.path_org + end return (route_a.priority or 0) > (route_b.priority or 0) end diff --git a/t/parameter.t b/t/parameter.t index 961779c..75bc4b5 100644 --- a/t/parameter.t +++ b/t/parameter.t @@ -428,3 +428,48 @@ match meta: metadata /name matched: {"_path":"/name/:name/","name":"json"} match meta: nil matched: [] + + + +=== TEST 13: route matching for routes with params and common prefix should not be dependent on registration order +--- config + location /t { + content_by_lua_block { + local json = require("toolkit.json") + local radix = require("resty.radixtree") + local rx = radix.new({ + { + paths = {"/api/:version/test/api/projects/:project_id/clusters/:cluster_id/nodes/?"}, + metadata = "long", + }, + { + paths = {"/api/:version/test/api/projects/:project_id"}, + metadata = "medium", + }, + { + paths = {"/api/:version/test/*subpath"}, + metadata = "short", + }, + }) + + -- should match long + local meta = rx:match("/api/v4/test/api/projects/saas/clusters/123/nodes/") + ngx.say("match meta: ", meta) + + -- should match short + local meta = rx:match("/api/v4/test/api") + ngx.say("match meta: ", meta) + + -- should match medium + local meta = rx:match("/api/v4/test/api/projects/saas") + ngx.say("match meta: ", meta) + } + } +--- request +GET /t +--- no_error_log +[error] +--- response_body +match meta: long +match meta: short +match meta: medium