cowboy_handler.erl (2211B)
1 %% Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu> 2 %% 3 %% Permission to use, copy, modify, and/or distribute this software for any 4 %% purpose with or without fee is hereby granted, provided that the above 5 %% copyright notice and this permission notice appear in all copies. 6 %% 7 %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 15 %% Handler middleware. 16 %% 17 %% Execute the handler given by the <em>handler</em> and <em>handler_opts</em> 18 %% environment values. The result of this execution is added to the 19 %% environment under the <em>result</em> value. 20 -module(cowboy_handler). 21 -behaviour(cowboy_middleware). 22 23 -export([execute/2]). 24 -export([terminate/4]). 25 26 -callback init(Req, any()) 27 -> {ok | module(), Req, any()} 28 | {module(), Req, any(), any()} 29 when Req::cowboy_req:req(). 30 31 -callback terminate(any(), map(), any()) -> ok. 32 -optional_callbacks([terminate/3]). 33 34 -spec execute(Req, Env) -> {ok, Req, Env} 35 when Req::cowboy_req:req(), Env::cowboy_middleware:env(). 36 execute(Req, Env=#{handler := Handler, handler_opts := HandlerOpts}) -> 37 try Handler:init(Req, HandlerOpts) of 38 {ok, Req2, State} -> 39 Result = terminate(normal, Req2, State, Handler), 40 {ok, Req2, Env#{result => Result}}; 41 {Mod, Req2, State} -> 42 Mod:upgrade(Req2, Env, Handler, State); 43 {Mod, Req2, State, Opts} -> 44 Mod:upgrade(Req2, Env, Handler, State, Opts) 45 catch Class:Reason:Stacktrace -> 46 terminate({crash, Class, Reason}, Req, HandlerOpts, Handler), 47 erlang:raise(Class, Reason, Stacktrace) 48 end. 49 50 -spec terminate(any(), Req | undefined, any(), module()) -> ok when Req::cowboy_req:req(). 51 terminate(Reason, Req, State, Handler) -> 52 case erlang:function_exported(Handler, terminate, 3) of 53 true -> 54 Handler:terminate(Reason, Req, State); 55 false -> 56 ok 57 end.