0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 12:20:24 +00:00
cowboy/test/handlers/ws_deflate_opts_h.erl
Loïc Hoguin 8164b50453
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.
2018-11-12 18:12:44 +01:00

36 lines
1.1 KiB
Erlang

%% 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}.