Skip to content

Commit

Permalink
Add on_request callback. (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
mworrell committed Jun 22, 2022
1 parent a056415 commit d17fa2d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ execute(Req, Env) ->
RequestContext = cowmachine_req:init_context(Req, EnvController, #{}),
% Set options for the cowmachine
Options = #{
on_request =>
fun(Ctx) ->
% Perform anything after initialization of your request
% Examples are checking special cookies, changing headers, etc.
Ctx
end,
on_welformed =>
fun(Ctx) ->
% Perform anything after well-formedness check of your request
Expand Down
8 changes: 6 additions & 2 deletions src/cowmachine.erl
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,15 @@ request_1(Controller, Req, Env, Options, Context) ->
ReqResult = try
EnvInit = cowmachine_req:init_env(Req, Env),
Context1 = cowmachine_req:set_env(EnvInit, Context),
case cowmachine_decision_core:handle_request(State, Context1) of
Context2 = case maps:get(on_request, Options, undefined) of
undefined -> Context1;
FunReq when is_function(FunReq) -> FunReq(Context1)
end,
case cowmachine_decision_core:handle_request(State, Context2) of
{_Finish, _StateResult, ContextResult} ->
ContextResult1 = case maps:get(on_handled, Options, undefined) of
undefined -> ContextResult;
Fun when is_function(Fun) -> Fun(ContextResult)
FunHandled when is_function(FunHandled) -> FunHandled(ContextResult)
end,
cowmachine_response:send_response(ContextResult1);
{upgrade, UpgradeFun, _StateResult, ContextResult} ->
Expand Down

0 comments on commit d17fa2d

Please sign in to comment.