Update: This post sparked my Webmachine nerve in such a way that I wrote four more posts about extending the resource described below. Read them if you'd like to see how this resource can evolve.
This morning I read a post about CouchDB's HTTP Handlers. Jón Grétar Borgþórsson demonstrates how one might implement a handler that serves a JSON structure describing the OS environment variables.
I thought that two additional pieces of code might be interesting. I'll lead with an example showing the most likely way this resource would have been coded for Webmachine:
The biggest difference to note between the Webmachine version and the CouchDB version is that the proper HTTP status codes are returned from the Webmachine resource. The CouchDB handler returns 500 or 405 when the requested resource is not found. The proper status for this case is 404. Webmachine knows this, and handles the choice automatically.
A little extra emphasis, I think, is appropriate here: Webmachine chooses the proper response code for you. You define methods that describe the state of your resource (like whether or not it exists, what methods it allows, etc.), and Webmachine negotiates the muck of HTTP.
As a bonus, the Webmachine resource is the same length, while at the same time being less dense and more readable.
Let's not get hasty, though. If there is a really good reason for returning an alternate status code, Webmachine won't get in your way. To prove it, here's a Webmachine resource that (as near as I can tell, I'm not a CouchDB guru) returns exactly the same statuses as the CouchDB handler:
Categories: Erlang Webmachine
Post Copyright © 2009 Bryan Fink