Anonymous committed 779ea7f

example of StreamBody

  • Participants
  • Parent commits 07092da

Comments (0)

Files changed (1)

 When a resource provides a body to be sent in the response, it should use {{{ wrq:set_resp_body/2 }}}.  The parameter to this function may be either an iolist, representing the entire body, or else a pair of the form {{{ {stream, StreamBody} }}}.
+An example may make the usage of this API clearer.  A complete and working resource module using this API in both directions:
+-export([init/1, allowed_methods/2, process_post/2]).
+init([]) -> {ok, undefined}.
+allowed_methods(ReqData, State) -> {['POST'], ReqData, State}.
+process_post(ReqData, State) ->
+    Body = get_streamed_body(wrq:stream_req_body(ReqData, 3), []),
+    {true, wrq:set_resp_body({stream, send_streamed_body(Body,4)},ReqData), State}.
+send_streamed_body(Body, Max) ->
+    HunkLen=8*Max,
+    case Body of        
+        <<A:HunkLen,Rest/binary>> ->
+            io:format("SENT ~p~n",[<<A:HunkLen>>]),
+            {<<A:HunkLen>>, fun() -> send_streamed_body(Rest,Max) end};
+        _ ->
+            io:format("SENT ~p~n",[Body]),
+            {Body, done}
+    end.
+get_streamed_body({Hunk,done},Acc) ->
+    io:format("RECEIVED ~p~n",[Hunk]),
+    iolist_to_binary(lists:reverse([Hunk|Acc]));
+get_streamed_body({Hunk,Next},Acc) ->
+    io:format("RECEIVED ~p~n",[Hunk]),
+    get_streamed_body(Next(),[Hunk|Acc]).
+If you use this resource in place of the [[QuickStart||quickstart]] resource module, you should then be able to issue {{{ curl -d '1234567890' }}} on the command line and the {{{ io:format }}} calls will show you what is going on.
+Obviously, a realistic resource wouldn't use this API just to collect the whole binary into memory or break one up that is already present -- you'd use {{{ req_body }} and put a simple iolist into {{{ set_resp_body }}} instead.  Also, the choices of 3 and 4 bytes as hunk size are far from optimal for most reasonable uses.  This resource is intended only as a demonstration of the API, not as a real-world use of streaming request/response bodies.