lua-resty-router

高性能路由器

$ opm get xiangnanscu/lua-resty-router

lua-resty-router

高性能路由器

路由器

创建

    ---@alias Route {[1]:string, [2]:function|string, [3]?:string|string[]}
    (method) Router:create(routes: Route[])
      -> Router

初始化一个带有路由的路由器

插入

    (method) Router:insert(path: string, handler: string|function, methods?: string|string[])
      -> Router

插入一个路由

匹配

    (method) Router:match(path: string, method: string)
      -> string|function
      2. { [string]: string|number }?

匹配一个 HTTP 请求

摘要

    local Router = require('resty.router')
    local tree = Router:create {
      { '/',                         'root',    { 'GET', 'patch' } },
      { '/v1',                       'v1',      'GET' },
      { '/number/#age',              'age',     'GET' },
      { '/all/:name',                'name',    'GET' },
      { '/regex/<version>\\d+-\\d+', 'version', 'GET' },
      { '/name',                     'name',    'GET' },
      { '/name/:name/age/#age',      'person',  'GET' },
      { '/v2',                       'v2',      'post' },
      { '/repo/:repo/path/*path',    'rest',    'get' },
    }
    
    local res, err, status = tree:match('/', 'POST')
    assert(res == nil and err == 'method not allowed' and status == 405)
    local res, params, status = tree:match('/v2/foo', 'GET')
    assert(res == nil and params == 'page not found' and status == 404)
    assert(tree:match('/', 'GET') == tree:match('/', 'PATCH'))
    assert(tree:match('/v1', 'GET') == 'v1')
    local res, params = tree:match('/number/#age', 'GET')
    assert(res == 'age')
    assert(params == nil)
    local res, params = tree:match('/number/23', 'GET')
    assert(res == 'age', 'res is :' .. tostring(res))
    assert(params.age == 23)
    local res, params = tree:match('/regex/1-3', 'GET')
    assert(res == 'version')
    assert(params.version == '1-3')
    local res, params = tree:match('/all/kate', 'GET')
    assert(res == 'name')
    assert(params.name == 'kate')
    local res, params = tree:match('/name/kate/age/23', 'GET')
    assert(res == 'person')
    assert(params.name == 'kate')
    assert(params.age == 23)
    assert(tree:match('/name', 'GET') == 'name')
    
    local res, params = tree:match('/repo/my_repo/path/lib/resty/router.lua', 'GET')
    assert(res == 'rest')
    assert(params.repo == 'my_repo')
    assert(params.path == '/lib/resty/router.lua')
    
    local tree = Router:new()
    tree:insert('/v1', 'v1')
    tree:post('/v2', 'v2')
    assert(tree:match('/v1', 'GET') == 'v1')
    assert(tree:match('/v2', 'POST') == 'v2')
    assert(tree:match('/v2', 'GET') == nil)
    
    print('all tests passed')

或者像这样

    local tree = Router:new()
    tree:insert('/v1', 'v1')
    tree:post('/v2', 'v2')
    assert(tree:match('/v1','GET') == 'v1')
    assert(tree:match('/v2','POST') == 'v2')
    assert(tree:match('/v2','GET') == nil)

作者

南向 (@xiangnanscu)

许可证

mit

版本