| 1 |
%% This module reads a multipart body and echoes it back as an Erlang term. |
| 2 |
|
| 3 |
-module(multipart_h). |
| 4 |
|
| 5 |
-export([init/2]). |
| 6 |
|
| 7 |
init(Req0, State) -> |
| 8 |
{Result, Req} = case cowboy_req:binding(key, Req0) of |
| 9 |
undefined -> acc_multipart(Req0, []); |
| 10 |
<<"skip_body">> -> skip_body_multipart(Req0, []); |
| 11 |
<<"read_part2">> -> read_part2_multipart(Req0, []); |
| 12 |
<<"read_part_body2">> -> read_part_body2_multipart(Req0, []) |
| 13 |
end, |
| 14 |
{ok, cowboy_req:reply(200, #{}, term_to_binary(Result), Req), State}. |
| 15 |
|
| 16 |
acc_multipart(Req0, Acc) -> |
| 17 |
case cowboy_req:read_part(Req0) of |
| 18 |
{ok, Headers, Req1} -> |
| 19 |
{ok, Body, Req} = stream_body(Req1, <<>>), |
| 20 |
acc_multipart(Req, [{Headers, Body}|Acc]); |
| 21 |
{done, Req} -> |
| 22 |
{lists:reverse(Acc), Req} |
| 23 |
end. |
| 24 |
|
| 25 |
stream_body(Req0, Acc) -> |
| 26 |
case cowboy_req:read_part_body(Req0) of |
| 27 |
{more, Data, Req} -> |
| 28 |
stream_body(Req, << Acc/binary, Data/binary >>); |
| 29 |
{ok, Data, Req} -> |
| 30 |
{ok, << Acc/binary, Data/binary >>, Req} |
| 31 |
end. |
| 32 |
|
| 33 |
skip_body_multipart(Req0, Acc) -> |
| 34 |
case cowboy_req:read_part(Req0) of |
| 35 |
{ok, Headers, Req} -> |
| 36 |
skip_body_multipart(Req, [Headers|Acc]); |
| 37 |
{done, Req} -> |
| 38 |
{lists:reverse(Acc), Req} |
| 39 |
end. |
| 40 |
|
| 41 |
read_part2_multipart(Req0, Acc) -> |
| 42 |
case cowboy_req:read_part(Req0, #{length => 1, period => 1}) of |
| 43 |
{ok, Headers, Req1} -> |
| 44 |
{ok, Body, Req} = stream_body(Req1, <<>>), |
| 45 |
acc_multipart(Req, [{Headers, Body}|Acc]); |
| 46 |
{done, Req} -> |
| 47 |
{lists:reverse(Acc), Req} |
| 48 |
end. |
| 49 |
|
| 50 |
read_part_body2_multipart(Req0, Acc) -> |
| 51 |
case cowboy_req:read_part(Req0) of |
| 52 |
{ok, Headers, Req1} -> |
| 53 |
{ok, Body, Req} = stream_body2(Req1, <<>>), |
| 54 |
acc_multipart(Req, [{Headers, Body}|Acc]); |
| 55 |
{done, Req} -> |
| 56 |
{lists:reverse(Acc), Req} |
| 57 |
end. |
| 58 |
|
| 59 |
stream_body2(Req0, Acc) -> |
| 60 |
case cowboy_req:read_part_body(Req0, #{length => 1, period => 1}) of |
| 61 |
{more, Data, Req} -> |
| 62 |
stream_body(Req, << Acc/binary, Data/binary >>); |
| 63 |
{ok, Data, Req} -> |
| 64 |
{ok, << Acc/binary, Data/binary >>, Req} |
| 65 |
end. |