Justin Sheehy posted here his webmachine version of a small but fun web application created originally in mochiweb by Hughes Waroquier from BeeBole. Hughes posted it in a form of neatscreencast tutorial. It’s worth watching.
Justin’s version is dated from October 22, 2008 and at that time webmachine version was < 1.0. Since that time the webmachine progressed and API has changed. Moreover, Justin’s great example is not a single file but rather code in-lined with post prose. His code has the static content delivery mixed-up with sticky notes resource. It also contained a security issue, which is using list_to_atombif with arbitrary arguments coming from API user, potentially opening door to blow our erlang VM’s memory up (running out of atoms).
Recently I was asked by my friend to introduce him Erlang webdevelopment. I though immediately about webmachine and the sweet sticky notes tutorial so I decided to create working code of that stuff. I have reused my static resource for webmachine resulting in having separation of Ajax API and static content delivery, reducing the original stickyNotes_webresource.erl to 18 lines of code.
-module(stickyNotes_webresource).
-export([init/1, process_post/2, allowed_methods/2]).
-include_lib("webmachine/include/webmachine.hrl").
init(Config) -> {{trace, "/tmp"}, Config}.
allowed_methods(ReqData, Context) ->
{['POST'], ReqData, Context}.
process_post(ReqData, Context) ->
Ps = mochiweb_util:parse_qs(wrq:req_body(ReqData)),
Struct = mochijson2:decode(proplists:get_value("json", Ps)),
Act = list_to_existing_atom(binary_to_list(struct:get_value(<<"action">>, Struct))),
Resp = wrq:merge_resp_headers([{"Content-Type", "application/json"}], ReqData),
Resp2 = wrq:append_to_response_body(mochijson2:encode(notes:Act(Struct)), Resp),
{true, Resp2, Context}.