From d17fa2d8717cbe94268ed957b904d0dd19d74c3f Mon Sep 17 00:00:00 2001 From: Marc Worrell Date: Wed, 22 Jun 2022 09:58:05 +0200 Subject: [PATCH] Add on_request callback. (#41) --- README.md | 6 ++++++ src/cowmachine.erl | 8 ++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5edd63d..185f299 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/cowmachine.erl b/src/cowmachine.erl index e617215..40cbc99 100644 --- a/src/cowmachine.erl +++ b/src/cowmachine.erl @@ -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} ->