在Lua NGINX中如何从POST JSON请求体提取param2值
在OpenResty Lua中提取POST请求体的param2值并匹配文件内容
一、提取POST请求体中的param2值
你的请求体是标准JSON格式,优先推荐用JSON解析库处理,比正则更可靠,能避免格式变动导致的匹配失败。
方法1:使用cjson库解析JSON(推荐)
OpenResty默认集成了cjson库,直接解析请求体即可提取参数:
-- 先确保读取请求体(若框架未自动读取) ngx.req.read_body() local check_body = ngx.req.get_body_data() -- 解析JSON并提取param2 local cjson = require("cjson.safe") local body_json = cjson.decode(check_body) local param2_value = nil if body_json and body_json.param2 then param2_value = body_json.param2 -- 直接拿到字符串格式的"337483",无需额外去引号 else -- 处理JSON解析失败或param2不存在的情况 ngx.log(ngx.ERR, "请求体解析失败或param2缺失") end
方法2:使用正则匹配(仿之前的Bash写法)
如果不想用JSON库,也可以用OpenResty的正则模块提取:
ngx.req.read_body() local check_body = ngx.req.get_body_data() -- 正则匹配param2的值,\K忽略前面的匹配内容 local _, _, param2_value = ngx.re.match(check_body, [[\s*"param2"\s*:\s*"(\d+)"]], "jo") if param2_value then -- param2_value就是提取到的数字字符串,比如"337483" else ngx.log(ngx.ERR, "无法从请求体中提取param2") end
注:该正则假设param2的值是带引号的数字,若值可能包含特殊字符,正则需要调整——这也是更推荐JSON解析的原因。
二、匹配文件中的数字行
拿到param2_value后,读取目标文件内容,检查是否存在完全匹配的行:
if param2_value then -- 替换成你的目标文件路径 local file_path = "/path/to/your/number_file.txt" local file, err = io.open(file_path, "r") if not file then ngx.log(ngx.ERR, "文件打开失败: ", err) return end local match_found = false -- 逐行读取文件 for line in file:lines() do -- 去除行首尾空白字符(换行、空格等) local trimmed_line = ngx.trim(line) if trimmed_line == param2_value then match_found = true break end end file:close() -- 匹配成功则执行后续逻辑 if match_found then ngx.log(ngx.INFO, "param2在文件中匹配成功: ", param2_value) -- 这里写入你要执行的命令/逻辑,比如调用接口、执行shell命令等 -- 示例:执行shell命令(注意安全风险) -- local cmd = "your_command_here" -- local handle = io.popen(cmd) -- local result = handle:read("*a") -- handle:close() else ngx.log(ngx.INFO, "param2未在文件中找到: ", param2_value) end end
内容的提问来源于stack exchange,提问作者Vancho
相关产品推荐
相关产品推荐

