From 08c2be058a1c376fcb80465473b53085c14f88f5 Mon Sep 17 00:00:00 2001 From: geeksilva97 Date: Thu, 18 Jan 2024 20:50:27 -0300 Subject: Fix match_qs with constraints when key is not present Original fix by Ali Farhadi . --- src/cowboy_req.erl | 7 ++++++- test/handlers/echo_h.erl | 1 + test/req_SUITE.erl | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/cowboy_req.erl b/src/cowboy_req.erl index 8edf4ff..995d67c 100644 --- a/src/cowboy_req.erl +++ b/src/cowboy_req.erl @@ -1024,7 +1024,12 @@ filter([], Map, Errors) -> _ -> {error, Errors} end; filter([{Key, Constraints}|Tail], Map, Errors) -> - filter_constraints(Tail, Map, Errors, Key, maps:get(Key, Map), Constraints); + case maps:find(Key, Map) of + {ok, Value} -> + filter_constraints(Tail, Map, Errors, Key, Value, Constraints); + error -> + filter(Tail, Map, Errors#{Key => required}) + end; filter([{Key, Constraints, Default}|Tail], Map, Errors) -> case maps:find(Key, Map) of {ok, Value} -> diff --git a/test/handlers/echo_h.erl b/test/handlers/echo_h.erl index f50bc79..d04d531 100644 --- a/test/handlers/echo_h.erl +++ b/test/handlers/echo_h.erl @@ -86,6 +86,7 @@ echo(<<"match">>, Req, Opts) -> Fields = [binary_to_atom(F, latin1) || F <- Fields0], Value = case Type of <<"qs">> -> cowboy_req:match_qs(Fields, Req); + <<"qs_with_constraints">> -> cowboy_req:match_qs([{id, integer}], Req); <<"cookies">> -> cowboy_req:match_cookies(Fields, Req); <<"body_qs">> -> %% Note that the Req should not be discarded but for the diff --git a/test/req_SUITE.erl b/test/req_SUITE.erl index 6e111bb..183bd4b 100644 --- a/test/req_SUITE.erl +++ b/test/req_SUITE.erl @@ -266,6 +266,7 @@ match_qs(Config) -> end, %% Ensure match errors result in a 400 response. {400, _, _} = do_get("/match/qs/a/c?a=b", [], Config), + {400, _, _} = do_get("/match/qs_with_constraints", [], Config), %% This function is tested more extensively through unit tests. ok. -- cgit v1.2.3