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

Add a commands-based interface to Websocket handlers

This feature is currently experimental. It will become the
preferred way to use Websocket handlers once it becomes
documented.

A commands-based interface enables adding commands without
having to change the interface much. It mirrors the interface
of stream handlers or gen_statem. It will enable adding
commands that have been needed for some time but were not
implemented for fear of making the interface too complex.
This commit is contained in:
Loïc Hoguin 2018-09-11 14:33:58 +02:00
parent 4b385749f2
commit 8404b1c908
No known key found for this signature in database
GPG key ID: 8A9DF795F6FED764
5 changed files with 342 additions and 4 deletions

View file

@ -0,0 +1,32 @@
%% This module takes commands from the x-commands header
%% and returns them in the websocket_info/2 callback.
%% This callback is triggered via a message.
-module(ws_info_commands_h).
-behavior(cowboy_websocket).
-export([init/2]).
-export([websocket_init/1]).
-export([websocket_handle/2]).
-export([websocket_info/2]).
init(Req=#{pid := Pid}, RunOrHibernate) ->
Commands0 = cowboy_req:header(<<"x-commands">>, Req),
Commands = binary_to_term(base64:decode(Commands0)),
case Commands of
bad -> ct_helper_error_h:ignore(Pid, cowboy_websocket, handler_call, 6);
_ -> ok
end,
{cowboy_websocket, Req, {Commands, RunOrHibernate}}.
websocket_init(State) ->
self() ! shoot,
{[], State}.
websocket_handle(_, State) ->
{[], State}.
websocket_info(_, State={Commands, run}) ->
{Commands, State};
websocket_info(_, State={Commands, hibernate}) ->
{Commands, State, hibernate}.