Adding response headers to static files

5 views
Skip to first unread message

Andy Shipman

unread,
Dec 10, 2009, 10:18:12 AM12/10/09
to me...@googlegroups.com
I'm interested in adding a far-forward expiry header to the Response when Merb (or rather Rack) serves static assets, specifically images. From what I've read it seems that Merb is using Merb::Rack::Static to serve static files:

(from my config.ru)

use Merb::Rack::Static, Merb.dir_for(:public)

This in turn is using ::Rack::File to serve the images:

    def serving
      if size = F.size?(@path)
        body = self
      else
        body = [F.read(@path)]
        size = Utils.bytesize(body.first)
      end

      [200, {
        "Last-Modified"  => F.mtime(@path).httpdate,
        "Content-Type"   => Mime.mime_type(F.extname(@path), 'text/plain'),
        "Content-Length" => size.to_s
      }, body]
    end

Ordinarily, the mtime of a file seems reasonable as a Last-Modified date, but as I'm using Heroku, I do a git push to that server and the mtime gets set to the current push time, not when the image last changed. Also, I'd like to add a Cache-Control header to the response as well and take advantage of the upstream HTTP accelerator that Heroku use, i.e. Varnish.

So, short of monkeypatching the Rack::File module, does anyone know of a way to hook into the serving process and add a header? Or is this something I need to ask the Rack list?

Thanks,

Andy Shipman





Andy Shipman

unread,
Dec 11, 2009, 1:27:05 PM12/11/09
to me...@googlegroups.com
I've read some more and discovered Rack::StaticCache in the rack-contrib github repository[1]. This does exactly what I was looking for and works a treat.

I'd certainly recommend it, should anyone else need to cache static assets.
Reply all
Reply to author
Forward
0 new messages