APItools / router.lua

A barebones router for Lua. It matches urls and executes lua functions.
MIT License
195 stars 47 forks source link

support hooks before and after execute handler #11

Closed lloydzhou closed 9 years ago

lloydzhou commented 9 years ago

i have write same library in PHP. https://github.com/lloydzhou/router

@kikito it's have a simple way to define and trigger hooks and error callback. so, i wish this project have the same function!

we can using hooks to format params, or run access check before action...

kikito commented 9 years ago

Hi there,

If I am understanding what you want to do with these "hooks", it is quite straightforward to transform a regular function into a function with hooks with plain Lua. You can do something like this:

local addHook = function(f, hook)
  return function(...)
    hook(...)
    return f(...)
  end
end

And then if you have this function and this hook:

local f = function(params)
  print(params.user)
end

local hook = function(params)
  params.user = "peter"
end

You can create "a hooked version of f" (which first calls hook, and then f) like this:

local hooked_f = addHook(f, hook)

And then use it in the router.

As I think this use case is covered well with plain Lua, I don't want to include it router.lua.

Regarding the errors, lua already provides an error-recovery mechanism. With no error-recovery mechanism you do this:

r:execute('GET',  '/hello')

If the function executed when resolving can throw an error, you can capture it with pcall:

local ok, err = pcall(r.execute, r, 'GET', '/foo')
if not ok then
  -- the variable err contains the error
end

Again, in this case I think plain Lua already handles the case well (or at least well enough to not need a specific construct in my library).

When doing libraries, I am a firm believer in the principle "Perfection is Achieved Not When There Is Nothing More to Add, But When There Is Nothing Left to Take Away" - The best code is no code.

I am not familiar enough with functions PHP. If they are able to be manipulated as they are in Lua, and if PHP has a similar error-handling mechanism to Lua, maybe you could consider removing the hooks and error callback from your library instead. That way our libraries would also be paired (and smaller, and thus more perfect :P)

In any case, I am closing this issue for now. Thank you for taking the time to open a ticket for it. I wish you good luck with your lib!

lloydzhou commented 9 years ago

Thank's for you reply!