Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix variable parsing when key is number #2964

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions rootfs/etc/nginx/lua/test/util_test.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
local original_ngx = ngx
local function reset_ngx()
_G.ngx = original_ngx
end

local function mock_ngx(mock)
local _ngx = mock
setmetatable(_ngx, { __index = ngx })
_G.ngx = _ngx
end

describe("lua_ngx_var", function()
local util = require("util")

before_each(function()
mock_ngx({ var = { remote_addr = "192.168.1.1", [1] = "nginx/regexp/1/group/capturing" } })
end)

after_each(function()
reset_ngx()
package.loaded["monitor"] = nil
end)

it("returns value of nginx var by key", function()
assert.equal("192.168.1.1", util.lua_ngx_var("$remote_addr"))
end)

it("returns value of nginx var when key is number", function()
assert.equal("nginx/regexp/1/group/capturing", util.lua_ngx_var("$1"))
end)

it("returns nil when variable is not defined", function()
assert.equal(nil, util.lua_ngx_var("$foo_bar"))
end)
end)
4 changes: 4 additions & 0 deletions rootfs/etc/nginx/lua/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ end
-- it returns value of ngx.var[request_uri]
function _M.lua_ngx_var(ngx_var)
local var_name = string_sub(ngx_var, 2)
if var_name:match("^%d+$") then
var_name = tonumber(var_name)
end

return ngx.var[var_name]
end

Expand Down