Lua模式匹配dyanmic url路径

时间:2016-02-25 19:21:14

标签: lua pattern-matching lua-patterns

我有一个要求,我必须更改并存储传入请求的动态网址路径并存储在我们的后端

以下是示例网址

GET /v1/merchants 

使用我的Lua代码,我将其更改为

GET_/v1/merchants

一切都很好,正是我所需要的。但是当我在url

中使用动态路径尝试时会出现问题

例如:GET /v1/content/merchants/{string}

网址可以是GET /v1/content/merchants/fooGET /v1/content/merchants/bar

我想将上述格式存储在后端,例如GET /v1/content/merchants/string,因为我无法在后端GET_/v1/content/merchants/fooGET_/v1/content/merchants/bar存储每个传入的请求

以下是代码

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

1 个答案:

答案 0 :(得分:0)

我建议使用

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"))

请参阅Lua demo

输出:

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

get_method_updated将确保您不会将强调的请求部分作为返回值。

相关问题