Rack :: ResponseHeaders适合Sinatra [英] Rack::ResponseHeaders in rackup for Sinatra
问题描述
我认为这是一件很容易的事情,但我似乎无法做到。基本上,我试图使用Rack中间件将默认的Cache-Control标头设置为由我的Sinatra应用程序提供的所有响应。它看起来像Rack :: ResponseHeaders应该能够做到我需要的东西,但是当我尝试使用 here 在我的rackup文件中:
使用Rack :: ResponseHeaders做|标题|
headers ['X-Foo'] ='bar'
headers.delete('X-Baz')
end
我能够使Rack :: Cache成功运行,如下所示:
使用Rack :: Cache,
:default_ttl => 3600
然而,这并不能达到我想要的输出,而Rack :: ResponseHeaders可以提供罚款
仅供参考,我的网站托管在Heroku上,所需的Rack宝石在我的.gems清单中指定。
谢谢!
更新:完成一些研究之后,在已安装的rack-contrib(0.9.2)版本中找不到Rack :: ResponseHeaders。
如果有人有兴趣,我可以得到这个工作。看起来,在Heroku上安装 rack-contrib-0.9.3
并不容易,但我需要的唯一文件是 response_headers.rb
,所以我简单地将它复制到我的项目目录中,并按如下方式编辑我的机架: require'rack / contrib / response_headers'
#设置默认缓存控制标题,如果没有设置Sinatra
使用Rack :: ResponseHeaders do | headers |
如果不是头['Cache-Control']
headers ['Cache-Control'] =public,max-age = 3600
end
end
这为未指定显式高速缓存控制标头的对象设置1小时的默认最大时间在Sinatra–即静态资产。
I think this is a very easy one, but I can't seem to get it right. Basically, I'm trying to use Rack middleware to set a default Cache-Control header into all responses served by my Sinatra app. It looks like Rack::ResponseHeaders should be able to do exactly what I need, but I get an error when attempting to use the syntax demonstrated here in my rackup file:
use Rack::ResponseHeaders do |headers|
headers['X-Foo'] = 'bar'
headers.delete('X-Baz')
end
I was able to get Rack::Cache to work successfully as follows:
use Rack::Cache,
:default_ttl => 3600
However, this doesn't achieve exactly the output I want, whereas Rack::ResponseHeaders gives fine-grained control of the headers.
FYI, my site is hosted on Heroku, and the required Rack gems are specified in my .gems manifest.
Thanks!
Update: After doing some research, it looks like the first issue is that Rack::ResponseHeaders is not found in the version of rack-contrib (0.9.2) which was installed. I'll start by looking into that.
In case anyone's interested, I was able to get this working. It didn't look like there would be an easy way to install rack-contrib-0.9.3
on Heroku, but the only file I needed was response_headers.rb
, so I simply copied this into my project directory and edited my rackup as follows:
require 'rack/contrib/response_headers'
# set default cache-control header if not set by Sinatra
use Rack::ResponseHeaders do |headers|
if not headers['Cache-Control']
headers['Cache-Control'] = "public, max-age=3600"
end
end
This sets a default max-age of 1 hr on objects for which I'm not specifying an explicit Cache-Control header in Sinatra – namely, static assets.
这篇关于Rack :: ResponseHeaders适合Sinatra的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!