I was bored last night, so I hacked this up. My original thought was
since riak has an HTTP interface, I could just proxy GET
requests to
it when a short URL was used, but either I was doing it wrong or you
can't set the Location
header when you POST
documents. Oh well.
Anyway, this uses riak just to store the URL, and the riak key as the short URL key. There is no error checking, UI, or anything fancy. It's pretty much the simplest thing that could possibly work.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
RIAK = ['localhost', 8098] | |
run lambda { |env| | |
req = Rack::Request.new(env) | |
if req.post? && req.path == '/' | |
res = Net::HTTP.new(*RIAK).start do |http| | |
http.post('/riak/shrt', req.params['url'], { 'Content-Type' => 'text/plain' }) | |
end | |
loc = [req.base_url, 'r', res['location'].split('/').last].join('/') | |
[res.code.to_i, { 'Content-Type' => 'text/plain', 'Location' => loc }, [res.message]] | |
elsif req.get? && req.path.start_with?('/r/') | |
key = req.path.split('/').last | |
res = Net::HTTP.new(*RIAK).start do |http| | |
http.get("/riak/shrt/#{key}") | |
end | |
[302, { 'Content-Type' => 'text/plain', 'Location' => res.body }, ['Redirecting...']] | |
else | |
[404, {'Content-Type' => 'text/plain'}, ['wat']] | |
end | |
} |
Also, it's kind of a lie, since the URLs it makes are actually a little long. Whatever.