Rack::ResponseHeaders in rackup for Sinatra

血红的双手。 提交于 2019-12-08 03:52:34

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2904462/rackresponseheaders-in-rackup-for-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!