You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx-Lua实现POST请求JSON字段与CSV文件精确匹配问题

解决CSV独立数值精确匹配问题

问题分析

原配置存在两个核心问题:

  • 匹配逻辑完全倒置:用目标数值去匹配整个文件内容,而非检查文件中是否存在独立行等于目标数值
  • 未按行处理CSV:直接读取整个文件字符串,会误匹配包含目标数值的其他行(如1283813122344中的12)

修改后的Nginx-Lua配置

location /reader_x {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Url-Scheme $scheme;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass_request_body on;
    proxy_pass_request_headers on;
    proxy_ssl_verify off;

    if ($request_method = POST ) {
        rewrite_by_lua '
            ngx.req.read_body()
            local check_body = ngx.req.get_body_data()
            local json = require "dkjson"
            local json_parse, err = json.decode(check_body)
            if not json_parse then
                ngx.log(ngx.ERR, "JSON解析失败: ", err)
                ngx.exit(400)
            end

            local target_num = json_parse.number_from_json
            if not target_num then
                ngx.log(ngx.ERR, "缺少number_from_json字段")
                ngx.exit(400)
            end

            local filepath = "/opt/file1.csv"
            local open_file, err = io.open(filepath, "r")
            if not open_file then
                ngx.log(ngx.ERR, "打开文件失败: ", err)
                ngx.exit(500)
            end

            local is_matched = false
            -- 逐行读取并匹配独立行
            for line in open_file:lines() do
                -- 去除行首尾空白(换行符、空格等)
                local trimmed_line = string.gsub(line, "^%s*(.-)%s*$", "%1")
                if trimmed_line == target_num then
                    is_matched = true
                    break
                end
            end
            io.close(open_file)

            if is_matched then
                ngx.say("this is exactly matched 12")
            else
                ngx.say("not matching")
            end
        ';
        proxy_pass https://localhost:8421 ;
    }
}

关键修改说明

  • 逐行处理文件:通过open_file:lines()遍历每一行,避免把整个文件作为单一匹配目标
  • 精确匹配逻辑:去除行首尾空白后,用==做完全相等判断,确保只匹配独立的12行
  • 增加错误处理:补充JSON解析失败、文件打开失败、字段缺失的日志和状态码,提升配置稳定性
  • 修正逻辑顺序:调整原代码中倒置的匹配逻辑,改为检查文件行是否等于目标数值

内容的提问来源于stack exchange,提问作者Vancho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:10:17