Skip to content

Instantly share code, notes, and snippets.

@vdel26
Last active January 12, 2016 14:12
Show Gist options
  • Save vdel26/ceaa8d3392af1783a55f to your computer and use it in GitHub Desktop.
Save vdel26/ceaa8d3392af1783a55f to your computer and use it in GitHub Desktop.
Memoize function "get_matched_rule"
local function memoize(fn)
local t = {}
return function(m,h,p,r)
local x, y
local key = j({m,h,p,tostring(r)}, string.char(28))
if t[key] then
x, y = t[key][1], t[key][2]
else
x, y = fn(m,h,p,r)
t[key] = {x,y}
end
return x, y
end
end
function M.get_matched_rule(method, hostname, path, rules)
local req = ("%s %s%s"):format(method, hostname, path)
for i=1, #rules do
local rule = rules[i]
-- pattern has the public host and pattern so public_host can be nil
local rule_host_pattern = ("^%s %s%s"):format(rule.method, (rule.public_host or ''), rule.pattern)
if req:match(rule_host_pattern) then
local match = req:match(rule_host_pattern)
local extra_path = req:sub(#match + 1)
return rule, extra_path
end
end
end
M.get_matched_rule = memoize(M.get_matched_rule)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment