compress_h.erl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. end,
  29. {ok, Req, State}.
  30. stream_reply(Headers, Req0) ->
  31. Data = lists:duplicate(10000, $a),
  32. Req = cowboy_req:stream_reply(200, Headers, Req0),
  33. _ = [cowboy_req:stream_body(Data, nofin, Req) || _ <- lists:seq(1,9)],
  34. cowboy_req:stream_body(Data, fin, Req),
  35. Req.