有人能解释下面的 LUA 代码是如何工作的吗?

我正在使用带有 lua 的 nginx。为了访问我的 ES 集群,我正在使用 lua 代码进行配置。我想知道代码是如何工作的...

-- 获取 URL
local uri = ngx.var.uri

-- 获取方法
local method = ngx.req.get_method()

local allowed  = false

for path, methods in pairs(restrictions[role]) do
  -- 路径匹配规则吗?
  local p = string.match(uri, path)

  -- 方法匹配规则吗?
  local m = nil
  for _, _method in pairs(methods) do
    m = m and m or string.match(method, _method)
  end

  if p and m then
    allowed = true
    break
  end
end

if not allowed then
  return write403Message()
end

假设URL: http://localhost/_GET方法:GET路径:/_GET 那么

local p = string.match(uri, path) -->那么 p 变量的值为 GET(即 p = GET)

如果我错了,请指正我?

for _, _method in pairs(methods) do
        m = m and m or string.match(method, _method)
      end

上面的片段将会做什么?

点赞
用户2858170
用户2858170

如果你想知道代码的作用,请参考 Lua 参考手册:

https://www.lua.org/manual/5.3/manual.html#pdf-string.match

如果你想了解 string.match 在你的示例中返回了什么,可以使用 print 函数。

比如:

p = string.match(uri, path)
print(p)

针对你的示例:

假设 URL 为:http://localhost/_GET,method:GET,路径为:/_GET,然后

local p = string.match(uri, path) --> 那么,p 变量就有了 GET 的值(即 p=GET)

p 实际上将指向 "/_GET"

/\_GET 是你的模式。string.match 将返回这个模式本身,因为这是一个很简单而明显的模式。

如果你想获取任何数字的匹配,那么你将从字符串中得到实际的数字。

2017-04-05 12:28:33