-
Notifications
You must be signed in to change notification settings - Fork 28
Middleware
Brian Zou edited this page Apr 22, 2020
·
6 revisions
HTTP middleware provides a convenient mechanism for filtering HTTP requests to your application.
All middleware must integrate IMiddleware and implement the name and onProcess methods. If only client IP=="10.1.11.31" is allowed to access, the others are forbidden; as shown below:
import hunt.framework.application.MiddlewareInterface;
///ip filter
class IpFilterMiddleware : MiddlewareInterface {
override string name() {
return IpFilterMiddleware.stringof;
}
//返回Response对象继续执行以后就不会访问到 Action 方法了,直接执行返回的 response 对象并且终止后面一切操作,对用户的请求进行拦截
override Response onProcess(Request request, Response response) {
if(request.remoteAddr() == "10.1.11.31")
{
response.setHttpError(403);
return response;
}
return null;
}
}
- Register global grouping middleware
It will be executed every time the action of the group is called. The registration method is as follows.
import hunt.framework;
void main()
{
//default admin api
app().addGroupMiddleware("default" , new IpFilterMiddleware());
}
- Register controller middleware
The middleware registered to the controller is executed every time the internal action is called. The registration method is as follows.
class UserController : Controller
{
///must be here
mixin MakeController;
this()
{
// Constructor code
this.addMiddleware(new UserMiddleware());
this.addMiddleware(new CheckIdMiddleware());
}
}