Commits

Anonymous committed 779ea7f

example of StreamBody

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:
 
+{{{
+#!erlang
+-module(mywebdemo_resource).
+-export([init/1, allowed_methods/2, process_post/2]).
 
+-include_lib("webmachine/include/webmachine.hrl").
+
+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' http://127.0.0.1:8000/ }}} 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.
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.