vinbha
vinbha

Reputation: 91

Lua pattern match for dyanmic url path

I have a requirement where I have to change and store the dynamic url path of the incoming request and store in our backend

Below is the sample url

GET /v1/merchants 

With my Lua code I change that to

GET_/v1/merchants

Everything is good and exactly what I need. But the problem arises when I try it with dynamic path in url

For eg: GET /v1/content/merchants/{string}

The url could be GET /v1/content/merchants/foo or GET /v1/content/merchants/bar

I want to store the above format in backend like GET /v1/content/merchants/string because I cannot store in backend GET_/v1/content/merchants/foo or GET_/v1/content/merchants/bar for every incoming request

Below is the code

local function get_method(request)
  local method, path, query_fragment = request:match("^(.+) ([^%?]+)(%??.*) .+$")
  if method and path then
    return method .. "_" .. path
  else
    return nil
  end
end

local function extract_usage(request)
  local usage_t =  {}
  local ts_method = get_method(request)
  if ts_method then
    usage_t[ts_method] = set_or_inc(usage_t, ts_method, 1)
    return build_querystring(usage_t)
  else
    return nil
  end
end

Upvotes: 1

Views: 1715

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

I suggest using

local function get_method_updated(request)
  local method, path, query_fragment = request:match("^(.+) ([^%?]+)(%??.*) .+$")
  if method and path then
    if path:match('^/[^/]+/[^/]+/[%w_]+') ~= nil then
        return method .. " " .. path
    else
        return method .. "_" .. path
    end 
  else
    return nil
  end
end

print(get_method_updated("GET /v1/merchants something"))
print(get_method_updated("GET /v1/content/merchants/foo or"))
print(get_method_updated("GET /v1/content/merchants/bar some"))

See the Lua demo.

Output:

GET_/v1/merchants
GET /v1/content/merchants/foo
GET /v1/content/merchants/bar

The get_method_updated will make sure you do not get the underscored request parts as the return value.

Upvotes: 0

Related Questions