使用中间件和控制器处理 HTTP 请求的区别
我正在使用 Ruby on Rails 3,我想知道使用中间件处理 HTTP 请求(拦截请求 URL 请求并执行响应)与控制器流(使用 respond_to
)处理有什么区别。
检查日志文件,我可以看到中间件加载和查询几乎就像调用控制器方法一样。这是因为,在后一种情况(调用控制器)中,如果 HTTP 请求是针对 JSON 数据的,RoR 不会渲染模板文件(这是一个“自动过程”?!)。
那么,你怎么看?
I am using Ruby on Rails 3 and I would like to know what difference there is on handling a HTTP request using middlewares (intercepting the request URL request and performing the response) than controllers flow (using respond_to
).
Inspecting the log file, I can see that middlewares load and query almost as if you were calling controller methods. This is because, in the latter case (calling controllers), RoR does not render template files (it is a "automatic process"?!) if the HTTP request is for JSON data.
So, what do you think about?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 Rack Middleware 的最大优点之一是您可以过滤响应 - 例如,以某种方式修改它,然后让它正常运行。查看标准 Rails 3 应用程序中的
rake middleware
,了解 Rails 用于执行会话、闪存存储等操作的所有中间件堆栈,甚至基于应用程序自己的routes.rb 进行路由
。当然,如果需要,中间件也可以终止响应过滤并充当请求端点。Rails Metal 是一个类似于中间件但充当端点的功能,它允许您在必要时从应用程序中获得一些额外的性能(假设您不需要完整的 Rails 堆栈)。
我建议您查看以下 Railscast:
One of the biggest advantages to using Rack Middleware is that you can filter the response--e.g., modify it in some way and then let it take its normal course. Take a look at
rake middleware
in a standard Rails 3 application to see all the middleware stack Rails uses to do things like sessions, flash storage, and even routing based on your application's ownroutes.rb
. Of course, a middleware may also terminate the response filtering and act as a request endpoint, if necessary.A feature similar to middleware, but that acts as an endpoint, is Rails Metal, allowing you to get some extra performance out of your app if necessary (assuming you don't need the full Rails stack).
I recommend you check out the following Railscasts: