为什么在nginx Lua处理请求时变量会被修改?

我刚开始学习Lua。

每次请求时,我想要检查请求参数中的name参数。但实际上,有时会发现self.name偶尔会改变。

例如,

请求A带有参数:request_id=123&name=ABC,
请求B带有参数:request_id=321&name=EFG,

在日志中,我发现有requests_id = 123,但name = EFG

为什么会这样?是我的类写错了吗?


下面是示例代码:

main.lua:

local checker = require "checker"
local ch = checker:new()


if ch:check_name() then
    ngx.header["Content-Type"] = "application/json"
    ngx.status = ngx.HTTP_FORBIDDEN
    ngx.exit(ngx.HTTP_FORBIDDEN)
end

checker.lua:

local utils = require "utils"

local _M = {}

function _M:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self

    self.args = utils.get_req_args() or {}

    local name = self.args["name"] or ""
    local request_id = self.args["request_id"] or ""

    self.name = name
    return o
end

function _M:check_name()
    ngx.log(ngx.ERR,"request_id: ",self.request_id," name: ",self.name)

    -- 进行一些检查...
end

utils.lua:

local json = require "cjson"

local _M = {}

function _M.new(self)
    return self
end

function _M.get_req_args()
    -- GET
    local args = nil
    if ngx.var.request_method == "GET" then
        args = ngx.req.get_uri_args()
    -- POST
    elseif ngx.var.request_method == "POST" then
        ngx.req.read_body()
        local data = ngx.req.get_body_data()
        args = json.decode(data)
    end
    return args
end
点赞