nginxluanginx-reverse-proxylua-tableopenresty

Lua exact match line from file


So here is my scenario :

I have nginx-lua config, that it contains json data (from POST request) :

{
    "profile_name": "test",
    "number_from_json": "12",
}

In my /opt/file1.csv

1283813122344
12
12838138931316
128381383131

I have

So I'm having this config

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 data = ngx.req.get_body_data()
   json = require "dkjson"
   local json_parse = json.decode(check_body)
   local number_cut = json_parse.number_from_json
   local filepath = "/opt/file1.csv"
   local open_file = io.open(filepath, "rb")
   local second_one = open_file:read("*a")
   io.close(open_file)
   local  match0 = string.match(number_cut, second_one)
   if match0 then
   ngx.say("this is exactly matched 12")
else
   ngx.say("not matching")
   end
   ';
proxy_pass https://localhost:8421 ;

So I need only to match 12 unique number, not if the other numbers are contains "12"

Let me know if you need more info


Solution

  • You may be using the string.match parameters switched.

    If I got the point, your question could be "how to match the whole word in Lua". This is a working example based on your scenario:

    local number_cut = 12
    local second_one = [[
    1283813122344
    12
    12838138931316
    128381383131
    ]]
    
    local match0 = string.match(second_one, "%f[%w_]" .. number_cut .. "%f[^%w_]")
    
    if (match0) then
        print "this is exactly matched 12"
    else
        print "not matching"
    end
    

    https://ideone.com/P18FxV

    Ref.: how to check if a word appears as a whole word in a string in Lua