Skip to content

Instantly share code, notes, and snippets.

@kylefox
Created September 21, 2012 06:05
Show Gist options
  • Save kylefox/3759958 to your computer and use it in GitHub Desktop.
Save kylefox/3759958 to your computer and use it in GitHub Desktop.
A little Goliath proof-of-concept for a dynamic custom origin for images in Amazon CloudFront
# This is a hack. Just playing around.
#
# Original image:
# http://media.photobattle.me.s3.amazonaws.com/images/5417/original.jpg
#
# To resize, use ImageMagick geometry strings (http://www.imagemagick.org/script/command-line-processing.php#geometry) in place of `original` in the URL.
#
# -- Examples --
#
# Proxies an existing image:
# http://localhost:9000/images/5417/original.jpg
#
# Resize to fit within 300x300 (no cropping, no upsizing):
# http://localhost:9000/images/5417/300x300>.jpg
#
# 50% of the original:
# http://localhost:9000/images/5417/50%.jpg
require 'goliath'
require 'cgi'
require 'em-synchrony/em-http'
require 'mini_magick'
class Chomper < Goliath::API
use Goliath::Rack::Validation::RequestMethod, %w(GET)
HOST = 'http://media.photobattle.me.s3.amazonaws.com'
def response(env)
key = env['PATH_INFO']
url = "#{HOST}#{key}"
resized_image = EM::HttpRequest.new(url).head
if resized_image.response_header.status == 200
# Resized photo already exists. Pass it along.
resized_image = EM::HttpRequest.new(url).get
logger.debug "File exists: #{url}"
return [200, {'X-Chomper' => 'Cache hit'}, resized_image.response]
else
_, __, id, format = CGI.unescape(key).split('/')
logger.debug "id: #{id}, format: #{format}"
source_url = "#{HOST}/images/#{id}/original.jpg"
logger.debug "Checking if source exists: #{source_url}"
source_image = EM::HttpRequest.new(source_url).get
image = MiniMagick::Image.read(source_image.response)
resize_cmd = format.gsub('.jpg', '')
logger.debug "Resize: #{resize_cmd}"
image.resize resize_cmd
stream = StringIO.new
image.write(stream)
return [200, {'X-Goliath' => 'Cache miss'}, stream.string]
end
[404, {'X-Goliath' => 'Proxy'}, "Not Found"]
end
end
# > ruby chomper.rb -sv
@jspaper
Copy link

jspaper commented Sep 9, 2013

Thanks for your sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment