Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTTP response (cache) headers in a Sinatra app hosted on Heroku

I have a fairly simple app (just one index.html file and a css file - it really is just a static page) hosted on Heroku.

I use Sinatra to host it on Heroku. The 'app' itself is fairly simple:

require 'rubygems'
require 'sinatra'

get "/" do
    File.read(File.join('public', 'index.html'))
end

The question is, how do I set the HTTP response header for the static assets? In particular, I wanted to set the Expires header for caching purposes.

EDIT: I'm looking to add the said header to the static assets (ie, the one that resides under /public, like background images, icons, etc)

like image 499
ryanprayogo Avatar asked Jan 27 '11 07:01

ryanprayogo


2 Answers

Apart from the fact that I wouldn't get through the Sinatra stack just to serve static files, you'd call

cache_control :public, max_age: 60

to cache for a minute. cache_control is a helper that comes with Sinatra.

Otherwise, I'd suggest you have a look at http://www.sinatrarb.com/configuration.html to see how Sinatra is set up so you don't have do deal with serving static files.

Hope this helps.

edit: I just saw you were explicitly asking for the Expires header. I'm not sure, but that should be fairly the same way as Cache-Control. Sorry for the confusion

like image 119
awendt Avatar answered Sep 28 '22 00:09

awendt


As an expansion to @awendt's answer, Sinatra can actually handle static files with out needing to explicitly define the route and print the file.

By adding:

set :static, true

..you can add your index.html and stylesheet.css to a public/ folder. Then when you visit http://localhost:9292/stylesheet.css you'll be provided with the static file.

If you want to use another folder name, instead of the default public/, then try:

set :public, "your_folder_name"

If we want to be less explicit we can just create the public/ folder in the knowledge that Sinatra will enable :static for us anyway :)

Source: http://www.sinatrarb.com/configuration.html#__enabledisable_static_file_routes

like image 24
Nick Avatar answered Sep 28 '22 00:09

Nick