Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Last active December 27, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igrigorik/7345973 to your computer and use it in GitHub Desktop.
Save igrigorik/7345973 to your computer and use it in GitHub Desktop.
source 'https://rubygems.org'
gem 'goliath'
GEM
remote: http://rubygems.org/
specs:
addressable (2.3.5)
async-rack (0.5.1)
rack (~> 1.1)
em-synchrony (1.0.3)
eventmachine (>= 1.0.0.beta.1)
em-websocket (0.3.8)
addressable (>= 2.1.1)
eventmachine (>= 0.12.9)
eventmachine (1.0.3)
goliath (1.0.3)
async-rack
em-synchrony (>= 1.0.0)
em-websocket (= 0.3.8)
eventmachine (>= 1.0.0.beta.4)
http_parser.rb (= 0.6.0.beta.2)
log4r
multi_json
rack (>= 1.2.2)
rack-contrib
rack-respond_to
http_parser.rb (0.6.0.beta.2)
log4r (1.1.10)
multi_json (1.8.2)
rack (1.5.2)
rack-accept-media-types (0.9)
rack-contrib (1.1.0)
rack (>= 0.9.1)
rack-respond_to (0.9.8)
rack-accept-media-types (>= 0.6)
PLATFORMS
ruby
DEPENDENCIES
goliath
<!DOCTYPE html>
<html>
<head>
<script>
function makeRequest(type) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/image.img');
xhr.setRequestHeader('Accept', type);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status == 200) {
var img = document.createElement('img');
img.src = window.URL.createObjectURL(this.response);
img.onload = function() {
window.URL.revokeObjectURL(this.src);
}
var title = document.createElement('h1');
title.innerHTML = type;
document.body.appendChild(title);
document.body.appendChild(img);
}
};
xhr.send();
}
if (location.search.indexOf("webp") !== -1) {makeRequest('image/webp')}
else if (location.search.indexOf("jpeg") !== -1) {makeRequest('image/jpeg')}
else {
makeRequest('image/jpeg');
makeRequest('image/webp');
}
</script>
</head>
<body>
<a href="/?webp">WebP</a>, <a href="/?jpeg">JPEG</a>, <a href="/">both</a>.
<p>Both image files are served from same URL but return either a JPEG or WebP based on advertised Accept header. Assuming there are no broken intermediary caches (i.e. that don't respect Vary: Accept), you should see two different images!</p>
</body>
</html>
web: bundle exec ruby server.rb -sv -e prod -p $PORT
require 'goliath'
class Server < Goliath::API
def response(env)
head = {}
resp = if env['REQUEST_PATH'] =~ /^\/image/
head['Vary'] = 'Accept'
head['Cache-Control'] = 'max-age=60'
if env['HTTP_ACCEPT'] =~ /webp/
head['Content-Type'] = 'image/webp'
IO.read('image.webp')
else
head['Content-Type'] = 'image/jpeg'
IO.read('image.jpg')
end
else
head['Content-Type'] = 'text/html'
head['Cache-Control'] = 'private, no-cache'
IO.read('index.html')
end
[200, head, resp]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment