Tuesday, April 28, 2009

A Simple Webmachine Example

Bryan Fink (of BeerRiot fame and a colleague at Basho) recently posted a great example of how easy it is to make a useful and working Webmachine resource.

He then followed up with more examples, showing how easy it is to add support for PUT, for authorization, and for
entity tags.

Yesterday's post wrapped up his short series by not only adding DELETE support but also reflecting on the nature of Webmachine and how it lets you improve the way you think about and use the power of HTTP in your applications.

Bryan knows both Erlang and Web programming well; his examples are worth the read.

4 comments:

Anonymous said...

Are there equivalents to django middleware and signals?

A middleware let you modify the request and response objects and used for authentication for example.

Signals are events that fire when a model has been saved or deleted for example.

Justin Sheehy said...

Anonymous,

Webmachine is different enough from Django that exact equivalents to many of that framework's elements don't quite make sense.

The main purposes of Middleware are generally just achieved via simple functions, since each of the resource functions (http://bitbucket.org/justin/webmachine/wiki/WebmachineResources) can accept and produce request/response data (http://bitbucket.org/justin/webmachine/wiki/WebmachineReqData) and can call arbitrary other functions. For instance, there's no reason why you couldn't have 10 different resource modules all sharing literally the same authorization function:

is_authorized(ReqData, State) -> my_app:is_auth(ReqData, State).

Much of the same applies to the uses that Django Signals are applied, and is made easier given that message passing is so effortless in Erlang. If you want something to send or receive messages, there's no extra plumbing needed.

The real story here is that Webmachine isn't meant to fully replace all of the things that a typical "framework" does for you. It helps you to build well-formed HTTP subsystems that can be part of applications larger than itself.

benoitc said...

how would you handle static files (js & ...) with webmachine ? is there any simple way to do it with mochiweb functions ?

Justin Sheehy said...

Excellent question, BenoƮt.

You ought to check out demo/src/demo_fs_resource.erl in the webmachine repo. It does far more than just what you asked, as it is a demo that shows remote creation and modification of "static" resources. If you just want to deliver files then a subset of that resource should work fine.

Enjoy!

-Justin