1. Bryan Fink
  2. wmexamples


Bryan Fink  committed a0bb705

add POST example in formjson_resource.erl

  • Participants
  • Parent commits 0cc7ce9
  • Branches default

Comments (0)

Files changed (3)


View file
 That resource isn't good for much other than generating those simple
 examples, but I thought it best to include it for demonstration
+POST Example (wwwform -> json)
+formjson_resource.erl is mainly an example of how one might handle a
+POST in a webmachine resource.  process_post/2 demonstrates how to
+grab the request body out of the ReqData (wrq:req_body/1), and push a
+response body into one (wrq:append_to_response_body/2).
+Issuing a GET to formjson_resource will encode the query parameters of
+the request as JSON, and return that encoding in the response body.
+Issuing a POST to formjson_resource will assume that the body of the
+request is application/x-www-form-urlencoded data, re-ecode it as
+JSON, and return that JSON in the response body.

File priv/dispatch.conf

View file
+%% x-www-form-urlencoded -> JSON translator
+%% Converts form data to JSON data.
+%% Try:
+%%    curl "http://localhost:8000/formjson?one=two&me=pope"
+%%    curl -X POST http://localhost:8000/formjson \
+%%         -d "one=two&me=pope"
+{["formjson"],      %% exposed at /formjson
+ formjson_resource, %% defined in formjson_resource
+ []}.               %% no configuration
 %% File Resource
 %% Serve files from disk.

File src/formjson_resource.erl

View file
+%% @author Bryan Fink
+%% @doc formjson_resource takes x-www-form-urlencoded data and
+%%      re-encodes it as JSON.  The data is expected as query
+%%      parameters for a GET, and request body for a POST.
+%%      In:  one=two&me=pope
+%%      Out: {"one":"two","me":"pope"}
+         allowed_methods/2,
+         content_types_provided/2,
+         to_json/2,
+         process_post/2]).
+init(_) -> {ok, undefined}.
+allowed_methods(RD, Ctx) ->
+    {['GET', 'HEAD', 'POST'], RD, Ctx}.
+content_types_provided(RD, Ctx) ->
+    {[{"application/json", to_json}], RD, Ctx}.
+%% hit this with
+%%   curl "http://localhost:8000/formjson?one=two&me=pope"
+to_json(RD, Ctx) ->
+    {json_body(wrq:req_qs(RD)), RD, Ctx}.
+%% hit this with
+%%   curl -X POST http://localhost:8000/formjson \
+%%        -d "one=two&me=pope"
+process_post(RD, Ctx) ->
+    Body = json_body(mochiweb_util:parse_qs(wrq:req_body(RD))),
+    {true, wrq:append_to_response_body(Body, RD), Ctx}.
+json_body(QS) -> mochijson:encode({struct, QS}).