Skip to content

Commit

Permalink
Merge pull request #2964 from Shopify/fix-upstreah-hash-by-number-key
Browse files Browse the repository at this point in the history
fix variable parsing when key is number
  • Loading branch information
k8s-ci-robot authored Aug 21, 2018
2 parents c083599 + 27cd1af commit a426fba
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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

0 comments on commit a426fba

Please sign in to comment.