2 %%! -smp disable +A1 +K true -pa ebin deps/cowboy/ebin -input
3 -module(cowboy_test_server).
9 -export([init/3, handle/2, terminate/2]).
14 application:start(sockjs),
15 application:start(cowboy),
17 StateEcho = sockjs_handler:init_state(
18 <<"/echo">>, fun service_echo/3, state,
19 [{response_limit, 4096}]),
20 StateClose = sockjs_handler:init_state(
21 <<"/close">>, fun service_close/3, state, []),
22 StateAmplify = sockjs_handler:init_state(
23 <<"/amplify">>, fun service_amplify/3, state, []),
24 StateBroadcast = sockjs_handler:init_state(
25 <<"/broadcast">>, fun service_broadcast/3, state, []),
26 StateDWSEcho = sockjs_handler:init_state(
27 <<"/disabled_websocket_echo">>, fun service_echo/3, state,
28 [{websocket, false}]),
29 StateCNEcho = sockjs_handler:init_state(
30 <<"/cookie_needed_echo">>, fun service_echo/3, state,
31 [{cookie_needed, true}]),
33 VRoutes = [{[<<"echo">>, '...'], sockjs_cowboy_handler, StateEcho},
34 {[<<"close">>, '...'], sockjs_cowboy_handler, StateClose},
35 {[<<"amplify">>, '...'], sockjs_cowboy_handler, StateAmplify},
36 {[<<"broadcast">>, '...'], sockjs_cowboy_handler, StateBroadcast},
37 {[<<"disabled_websocket_echo">>, '...'], sockjs_cowboy_handler,
39 {[<<"cookie_needed_echo">>, '...'], sockjs_cowboy_handler,
42 Routes = [{'_', VRoutes}], % any vhost
44 io:format(" [*] Running at http://localhost:~p~n", [Port]),
45 cowboy:start_listener(http, 100,
46 cowboy_tcp_transport, [{port, Port}],
47 cowboy_http_protocol, [{dispatch, Routes}]),
52 %% --------------------------------------------------------------------------
54 init({_Any, http}, Req, []) ->
58 {ok, Req2} = cowboy_http_req:reply(404, [],
59 <<"404 - Nothing here (via sockjs-erlang fallback)\n">>, Req),
62 terminate(_Req, _State) ->
65 %% --------------------------------------------------------------------------
67 service_echo(_Conn, init, state) -> {ok, state};
68 service_echo(Conn, {recv, Data}, state) -> Conn:send(Data);
69 service_echo(_Conn, closed, state) -> {ok, state}.
71 service_close(Conn, _, _State) ->
72 Conn:close(3000, "Go away!").
74 service_amplify(Conn, {recv, Data}, _State) ->
75 N0 = list_to_integer(binary_to_list(Data)),
76 N = if N0 > 0 andalso N0 < 19 -> N0;
79 Conn:send(list_to_binary(
80 string:copies("x", round(math:pow(2, N)))));
81 service_amplify(_Conn, _, _State) ->
84 service_broadcast(Conn, init, _State) ->
85 case ets:info(broadcast_table, memory) of
87 ets:new(broadcast_table, [public, named_table]);
91 true = ets:insert(broadcast_table, {Conn}),
93 service_broadcast(Conn, closed, _State) ->
94 true = ets:delete_object(broadcast_table, {Conn}),
96 service_broadcast(_Conn, {recv, Data}, _State) ->
97 ets:foldl(fun({Conn1}, _Acc) -> Conn1:send(Data) end,