compress_h.erl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. %% This module sends a response body of varying sizes to test
  2. %% the cowboy_compress_h stream handler.
  3. -module(compress_h).
  4. -export([init/2]).
  5. init(Req0, State=reply) ->
  6. Req = case cowboy_req:binding(what, Req0) of
  7. <<"small">> ->
  8. cowboy_req:reply(200, #{}, lists:duplicate(100, $a), Req0);
  9. <<"large">> ->
  10. cowboy_req:reply(200, #{}, lists:duplicate(100000, $a), Req0);
  11. <<"over-threshold">> ->
  12. cowboy_req:reply(200, #{}, lists:duplicate(200, $a), Req0);
  13. <<"content-encoding">> ->
  14. cowboy_req:reply(200, #{<<"content-encoding">> => <<"compress">>},
  15. lists:duplicate(100000, $a), Req0);
  16. <<"sendfile">> ->
  17. AppFile = code:where_is_file("cowboy.app"),
  18. Size = filelib:file_size(AppFile),
  19. cowboy_req:reply(200, #{}, {sendfile, 0, Size, AppFile}, Req0)
  20. end,
  21. {ok, Req, State};
  22. init(Req0, State=stream_reply) ->
  23. Req = case cowboy_req:binding(what, Req0) of
  24. <<"large">> ->
  25. stream_reply(#{}, Req0);
  26. <<"content-encoding">> ->
  27. stream_reply(#{<<"content-encoding">> => <<"compress">>}, Req0);
  28. <<"sendfile">> ->
  29. Data = lists:duplicate(10000, $a),
  30. AppFile = code:where_is_file("cowboy.app"),
  31. Size = filelib:file_size(AppFile),
  32. Req1 = cowboy_req:stream_reply(200, Req0),
  33. %% We send a few files interspersed into other data.
  34. cowboy_req:stream_body(Data, nofin, Req1),
  35. cowboy_req:stream_body({sendfile, 0, Size, AppFile}, nofin, Req1),
  36. cowboy_req:stream_body(Data, nofin, Req1),
  37. cowboy_req:stream_body({sendfile, 0, Size, AppFile}, nofin, Req1),
  38. cowboy_req:stream_body(Data, fin, Req1),
  39. Req1;
  40. <<"sendfile_fin">> ->
  41. Data = lists:duplicate(10000, $a),
  42. AppFile = code:where_is_file("cowboy.app"),
  43. Size = filelib:file_size(AppFile),
  44. Req1 = cowboy_req:stream_reply(200, Req0),
  45. %% We send a few files interspersed into other data.
  46. cowboy_req:stream_body(Data, nofin, Req1),
  47. cowboy_req:stream_body({sendfile, 0, Size, AppFile}, nofin, Req1),
  48. cowboy_req:stream_body(Data, nofin, Req1),
  49. cowboy_req:stream_body({sendfile, 0, Size, AppFile}, fin, Req1),
  50. Req1
  51. end,
  52. {ok, Req, State}.
  53. stream_reply(Headers, Req0) ->
  54. Data = lists:duplicate(10000, $a),
  55. Req = cowboy_req:stream_reply(200, Headers, Req0),
  56. _ = [cowboy_req:stream_body(Data, nofin, Req) || _ <- lists:seq(1,9)],
  57. cowboy_req:stream_body(Data, fin, Req),
  58. Req.