Rails 3中间件修改请求标头
我的设置:Rails 3.0.9,Ruby 1.9.2
我正在开发我的第一个中间件应用程序,似乎所有示例都涉及修改响应。我需要特别检查和修改请求标头,删除一些导致 Rack 1.2.3 中的错误阻塞的违规标头。这是典型的 hello world Rack 应用程序。
my_middleware.rb
class MyMiddleware
def initialize(app)
@app = app
end
def call(env)
@status, @headers, @response = @app.call(env)
[@status, @headers, @response]
end
end
有没有人有一个例子来处理请求头并在 Rack 掌握它之前拦截它们?我需要在请求头到达 Rack 进行解析之前修改它。我有这样的设置,认为将它放在 Rack 之前可能会成功,但我不确定执行顺序是否以这种方式强制执行。
application.rb
config.middleware.insert_before Rack::Lock, "MyMiddleware"
My setup: Rails 3.0.9, Ruby 1.9.2
I am working on my first middleware app and it seems like all of the examples deal with modify the response. I need to examine and modify the request headers in particular, delete some offending headers that cause a bug in Rack 1.2.3 to choke. Here's the typical hello world Rack app.
my_middleware.rb
class MyMiddleware
def initialize(app)
@app = app
end
def call(env)
@status, @headers, @response = @app.call(env)
[@status, @headers, @response]
end
end
Does anyone have an example that deals with the request headrers and intercepting them before Rack gets hold of it? I need to modify the request headers before it gets to Rack for parsing. I have this setup, thinking that putting it before Rack might do the trick but I am not sure if order of execution is enforced in this manner.
application.rb
config.middleware.insert_before Rack::Lock, "MyMiddleware"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的
call
方法中,您应该能够修改env
,即机架环境。 Rack 在每个标头前添加HTTP_
,因此可以通过env['HTTP_ACCEPT']
访问Accept
标头。因此,如果您需要删除某些标头,您应该能够执行诸如
env.delete('HTTP_ACCEPT')
之类的操作。然后,当您执行@app.call(env)
时,它将使用您修改后的env
。有关
env
对象的更多信息,请参阅Rack 文档(请参阅“环境” )。In your
call
method, you should be able to modifyenv
, which is the Rack Environment. Rack prependsHTTP_
to each header, so theAccept
header would be accessed viaenv['HTTP_ACCEPT']
.So if you need to delete certain headers, you should be able to do something like
env.delete('HTTP_ACCEPT')
. Then when you do@app.call(env)
, it will use your modifiedenv
.See the Rack documentation for more information on the
env
object (see "The Environment").