Saturday, September 10, 2011

Using Goliath as an API Proxy

I recently set up a proxy server using Goliath, a new asynchronous web server from Postrank Labs. I'm building an app that allows users to provision phone numbers from Twilio. To find numbers, I was making calls on the user's behalf to Twilio's AvailablePhoneNumber API. Since our server wasn't doing anything with the data except passing it back to the client, I wondered if it might be easier to setup a web proxy which rewrites the browser's request for data by adding private API credentials to each request, and passes the data through without doing any sort of processing.

Then I read Gabe Weinberg's post on cool Nginx hacks where he describes this exact technique under the heading "Proxy external JSON calls". Unfortunately this app is hosted on Heroku so my solution is a little more involved than changing an Nginx config. Goliath turned out to be perfect for it, though:

That code takes requests for Local or TollFree numbers, signs them with my Twilio credentials, and proxies the connection. I have it running on an isolated Heroku app on a separate domain from the rest of my app (since the original app is not running on Goliath) which is why I'm using the JSONP middleware (so the browser can make JSONP requests for this data, avoiding cross-site security restrictions). Twilio gives pretty good error messages in the body of its response which is why I'm returning 200 for all requests. The client can inspect the returned data to see if there were problems with the request.

By the way the Procfile that run this code on Heroku is simply:

web: bundle exec ruby lib/twilio.rb -sv -p $PORT -e prod