mirror of
https://github.com/ninenines/cowboy.git
synced 2025-07-14 12:20:24 +00:00
Introduce Handler:init/2 for initializing the handler state.
We need an init function in order to process upgrade instructions for protocols like WebSockets, but also to request an active receive mode for long-polling connections, both of which will be implemented at a later time.
This commit is contained in:
parent
a77b906b9f
commit
f53235549d
2 changed files with 20 additions and 7 deletions
|
@ -63,7 +63,10 @@ use one of the predefined handlers or write your own. An hello world HTTP
|
||||||
handler could be written like this:
|
handler could be written like this:
|
||||||
|
|
||||||
-module(my_handler).
|
-module(my_handler).
|
||||||
-export([handle/2]).
|
-export([init/2, handle/2]).
|
||||||
|
|
||||||
handle(Opts, Req) ->
|
init(Req, Opts) ->
|
||||||
|
{ok, undefined}.
|
||||||
|
|
||||||
|
handle(Req, State) ->
|
||||||
{reply, 200, [], "Hello World!"}.
|
{reply, 200, [], "Hello World!"}.
|
||||||
|
|
|
@ -106,14 +106,24 @@ header({http_header, _I, Field, _R, Value}, Req, State) ->
|
||||||
header(http_eoh, #http_req{host=undefined}, State) ->
|
header(http_eoh, #http_req{host=undefined}, State) ->
|
||||||
error_terminate(400, State);
|
error_terminate(400, State);
|
||||||
header(http_eoh, Req, State) ->
|
header(http_eoh, Req, State) ->
|
||||||
handler_loop(Req, State).
|
handler_init(Req, State).
|
||||||
|
|
||||||
-spec handler_loop(Req::#http_req{}, State::#state{}) -> ok.
|
-spec handler_init(Req::#http_req{}, State::#state{}) -> ok.
|
||||||
handler_loop(Req, State=#state{handler={Handler, Opts}}) ->
|
handler_init(Req, State=#state{handler={Handler, Opts}}) ->
|
||||||
case Handler:handle(Opts, Req) of
|
case Handler:init(Req, Opts) of
|
||||||
|
{ok, HandlerState} ->
|
||||||
|
handler_loop(HandlerState, Req, State)
|
||||||
|
%% @todo {mode, active}; {upgrade_protocol, Module}; {error, Reason}
|
||||||
|
end.
|
||||||
|
|
||||||
|
-spec handler_loop(HandlerState::term(), Req::#http_req{},
|
||||||
|
State::#state{}) -> ok.
|
||||||
|
handler_loop(HandlerState, Req, State=#state{handler={Handler, _Opts}}) ->
|
||||||
|
case Handler:handle(Req, HandlerState) of
|
||||||
|
%% @todo {ok, HandlerState}; {mode, active}
|
||||||
|
%% @todo Move the reply code to the cowboy_http_req module.
|
||||||
{reply, RCode, RHeaders, RBody} ->
|
{reply, RCode, RHeaders, RBody} ->
|
||||||
reply(RCode, RHeaders, RBody, State)
|
reply(RCode, RHeaders, RBody, State)
|
||||||
%% @todo stream_reply, request_body, stream_request_body...
|
|
||||||
end.
|
end.
|
||||||
|
|
||||||
-spec error_terminate(Code::http_status(), State::#state{}) -> ok.
|
-spec error_terminate(Code::http_status(), State::#state{}) -> ok.
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue