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

Add deflate options for Websocket compression

They allow the server to configure what it is willing to accept
for both the negotiated configuration (takeover and window bits)
and the other zlib options (level, mem_level and strategy).

This can be used to reduce the memory and/or CPU footprint of
the compressed data, which comes with a cost in compression ratio.
This commit is contained in:
Loïc Hoguin 2018-11-12 18:12:44 +01:00
parent fe1ee080de
commit 8164b50453
No known key found for this signature in database
GPG key ID: 8A9DF795F6FED764
4 changed files with 220 additions and 50 deletions

View file

@ -0,0 +1,36 @@
%% This module enables compression and returns deflate
%% options depending on the query string.
-module(ws_deflate_opts_h).
-behavior(cowboy_websocket).
-export([init/2]).
-export([websocket_handle/2]).
-export([websocket_info/2]).
init(Req=#{qs := Qs}, State) ->
{Name, Value} = case Qs of
<<"server_context_takeover">> -> {server_context_takeover, takeover};
<<"server_no_context_takeover">> -> {server_context_takeover, no_takeover};
<<"client_context_takeover">> -> {client_context_takeover, takeover};
<<"client_no_context_takeover">> -> {client_context_takeover, no_takeover};
<<"server_max_window_bits">> -> {server_max_window_bits, 9};
<<"client_max_window_bits">> -> {client_max_window_bits, 9};
<<"level">> -> {level, best_speed};
<<"mem_level">> -> {mem_level, 1};
<<"strategy">> -> {strategy, rle}
end,
{cowboy_websocket, Req, State, #{
compress => true,
deflate_opts => #{Name => Value}
}}.
websocket_handle({text, Data}, State) ->
{reply, {text, Data}, State};
websocket_handle({binary, Data}, State) ->
{reply, {binary, Data}, State};
websocket_handle(_, State) ->
{ok, State}.
websocket_info(_, State) ->
{ok, State}.