0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 20:30:23 +00:00

Add the set_options stream handler command

The first two options to benefit from this are the
cowboy_compress_h options.
This commit is contained in:
Loïc Hoguin 2018-11-15 18:53:42 +01:00
parent fbfec873f6
commit 240da3f2d9
No known key found for this signature in database
GPG key ID: 8A9DF795F6FED764
5 changed files with 151 additions and 39 deletions

View file

@ -34,10 +34,7 @@
init(StreamID, Req, Opts) ->
State0 = check_req(Req),
CompressThreshold = maps:get(compress_threshold, Opts, 300),
DeflateFlush = case maps:get(compress_buffering, Opts, false) of
false -> sync;
true -> none
end,
DeflateFlush = buffering_to_zflush(maps:get(compress_buffering, Opts, false)),
{Commands0, Next} = cowboy_stream:init(StreamID, Req, Opts),
fold(Commands0, State0#state{next=Next,
threshold=CompressThreshold,
@ -143,10 +140,24 @@ fold([Data0={data, _, _}|Tail], State0=#state{compress=gzip}, Acc) ->
fold([Trailers={trailers, _}|Tail], State0=#state{compress=gzip}, Acc) ->
{{data, fin, Data}, State} = gzip_data({data, fin, <<>>}, State0),
fold(Tail, State, [Trailers, {data, nofin, Data}|Acc]);
%% All the options from this handler can be updated for the current stream.
fold([{set_options, Opts}|Tail], State=#state{
threshold=CompressThreshold0, deflate_flush=DeflateFlush0}, Acc) ->
CompressThreshold = maps:get(compress_threshold, Opts, CompressThreshold0),
DeflateFlush = case Opts of
#{compress_buffering := CompressBuffering} ->
buffering_to_zflush(CompressBuffering);
_ ->
DeflateFlush0
end,
fold(Tail, State#state{threshold=CompressThreshold, deflate_flush=DeflateFlush}, Acc);
%% Otherwise, we have an unrelated command or compression is disabled.
fold([Command|Tail], State, Acc) ->
fold(Tail, State, [Command|Acc]).
buffering_to_zflush(true) -> none;
buffering_to_zflush(false) -> sync.
gzip_response({response, Status, Headers, Body}, State) ->
%% We can't call zlib:gzip/1 because it does an
%% iolist_to_binary(GzBody) at the end to return

View file

@ -41,6 +41,7 @@
| {error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
| {switch_protocol, cowboy:http_headers(), module(), state()}
| {internal_error, any(), human_reason()}
| {set_options, map()}
| {log, logger:level(), io:format(), list()}
| stop].
-export_type([commands/0]).

View file

@ -227,6 +227,9 @@ info(StreamID, Push={push, _, _, _, _, _, _, _}, State) ->
do_info(StreamID, Push, [Push], State);
info(StreamID, SwitchProtocol={switch_protocol, _, _, _}, State) ->
do_info(StreamID, SwitchProtocol, [SwitchProtocol], State#state{expect=undefined});
%% Convert the set_options message to a command.
info(StreamID, SetOptions={set_options, _}, State) ->
do_info(StreamID, SetOptions, [SetOptions], State);
%% Unknown message, either stray or meant for a handler down the line.
info(StreamID, Info, State) ->
do_info(StreamID, Info, [], State).