Add middleware support (#779)
This commit partially resolves #24, which is a common requirement on
many RESTful services.
A vector of middleware handlers is added to Router, these handlers are
executed before the URL match and handler invocation, in the order of
registration.
A middleware function has the signature:
bool func(Pistache::Http::Request &request,
Pistache::Http::ResponseWriter &response);
The first parameter is a reference to Http::Request, not Rest::Request,
at the moment middlewares are called, the request parameters are not yet
filled. This allows some generic operation on the request, such as
authentication or rate limiting.
Parameters are passed as references, to allow the middlewares be able to
modify them, such as injecting custom headers.
If a function returns true, the next function is executed, until all
middleware functions are called and all of them return true, the
registered handler is called.
If one of them returns false, this means there is no need to further
call the subsequent functions and the handler, the handling of this
request completes. Typical case is missing auth info or reaching limit.
Basically, the middleware function that returns false is responsible to
call response.send() to send the response to client.
Like Route::bind, a new method, Route::middleware(), with different
signatures, is added, to convert different callables into a middleware.
There is also requirements on the "post-handling" handlers, such as
logging response, measuring handler latency, and so on, in a centralized
place. This commit doesn't implement it: The response is passed to
handler using std::move, it's not retrievable again after handler
processing.
Signed-off-by: Jiankun Yu <yujiankun@hotmail.com>
Showing
Please register or sign in to comment