Skip to content

Commit 7f2fde0

Browse files
authored
optimize: cache reversed host string. (#21)
1 parent 57a869e commit 7f2fde0

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

lib/resty/radixtree.lua

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -215,24 +215,29 @@ local function pre_insert_route(self, path, route)
215215
if type(hosts) == "table" and #hosts > 0 then
216216
route_opts.hosts = {}
217217
for _, h in ipairs(hosts) do
218-
local host_is_wildcard = false
218+
local is_wildcard = false
219219
if h and h:sub(1, 1) == '*' then
220-
host_is_wildcard = true
220+
is_wildcard = true
221221
h = h:sub(2):reverse()
222+
else
223+
h = h:reverse()
222224
end
223225

224-
insert_tab(route_opts.hosts, host_is_wildcard)
226+
insert_tab(route_opts.hosts, is_wildcard)
225227
insert_tab(route_opts.hosts, h)
226228
end
227229

228230
elseif type(hosts) == "string" then
229-
local host_is_wildcard = false
230-
if hosts and hosts:sub(1, 1) == '*' then
231-
host_is_wildcard = true
232-
hosts = hosts:sub(2):reverse()
231+
local is_wildcard = false
232+
local host = hosts
233+
if host:sub(1, 1) == '*' then
234+
is_wildcard = true
235+
host = host:sub(2):reverse()
236+
else
237+
host = host:reverse()
233238
end
234239

235-
route_opts.hosts = {host_is_wildcard, hosts}
240+
route_opts.hosts = {is_wildcard, host}
236241
end
237242

238243
local uris = route.uris
@@ -350,7 +355,7 @@ local function match_host(route_host_is_wildcard, route_host, request_host)
350355
return route_host == request_host
351356
end
352357

353-
local i = request_host:reverse():find(route_host, 1, true)
358+
local i = request_host:find(route_host, 1, true)
354359
if i ~= 1 then
355360
return false
356361
end
@@ -432,11 +437,19 @@ local function match_route_opts(route, opts)
432437
-- log_info("route.hosts: ", type(route.hosts))
433438
if route.hosts then
434439
local matched = false
440+
441+
if opts.host and not opts.host_reversed then
442+
opts.host_reversed = opts.host:reverse()
443+
end
444+
435445
local hosts = route.hosts
436-
for i = 1, #hosts, 2 do
437-
if match_host(hosts[i], hosts[i + 1], opts.host) then
438-
matched = true
439-
break
446+
local reverse_host = opts.host_reversed
447+
if reverse_host then
448+
for i = 1, #hosts, 2 do
449+
if match_host(hosts[i], hosts[i + 1], reverse_host) then
450+
matched = true
451+
break
452+
end
440453
end
441454
end
442455

0 commit comments

Comments
 (0)