Skip to content

Instantly share code, notes, and snippets.

@tarnacious
Created January 28, 2011 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarnacious/800086 to your computer and use it in GitHub Desktop.
Save tarnacious/800086 to your computer and use it in GitHub Desktop.
A webmachine guestbook! Although a little hacky :)
#! src/guestbook_resource.erl
-module(guestbook_resource).
-export([init/1,
to_html/2,
process_post/2,
allowed_methods/2
]).
-include_lib("webmachine/include/webmachine.hrl").
init([]) -> {ok, undefined}.
allowed_methods(Request, Context) ->
{['GET', 'HEAD', 'POST'], Request, Context}.
to_html(Request, Context) ->
%% Load some messages from my mnesia store from the tutorial
Messages = message_store:find_messages("everyone"),
%% Render a template
{ok, Content} = index_dtl:render([{messages,Messages}]),
{Content, Request, Context}.
process_post(Request, Context) ->
%% Get message from post data
Post = mochiweb_util:parse_qs(wrq:req_body(Request)),
Message = proplists:get_value("message", Post),
%% Store it in my mnesia store, from the erlang tutorial
message_store:save_message("everyone",Message),
%% Maybe a bit hacky? Should really be exporting moved_temporarily ;)
Response = wrq:do_redirect(true, wrq:set_resp_header("location", "/", Request)),
{true, Response, Context}.
#! templates/index.index.dtl
<html>
<head>
<title>Guestbook</title>
</head>
<body>
<h1>Guestbook</h1>
<form action="/" method="post">
<input type="text" name="message" />
<input type="submit" value="Submit" />
</form>
{% for i in messages %}
<div>
{{ i }}
</div>
{% endfor %}
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment