Skip to content

Commit

Permalink
Merge pull request #79 from marianovalles/master
Browse files Browse the repository at this point in the history
Decode URI params when using elli_request:get_arg/3
  • Loading branch information
knutin committed Apr 14, 2014
2 parents 4627737 + 3f8830f commit 49cd96e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/elli_example_callback.erl
Expand Up @@ -46,6 +46,11 @@ handle('GET', [<<"hello">>, <<"iolist">>], Req) ->
Name = elli_request:get_arg(<<"name">>, Req),
{ok, [], [<<"Hello ">>, Name]};

handle('GET', [<<"decoded-hello">>], Req) ->
%% Fetch a URI decoded GET argument from the URL.
Name = elli_request:get_arg_decoded(<<"name">>, Req, <<"undefined">>),
{ok, [], <<"Hello ", Name/binary>>};

handle('GET', [<<"type">>], Req) ->
Name = elli_request:get_arg(<<"name">>, Req),
%% Fetch a header.
Expand Down
9 changes: 9 additions & 0 deletions src/elli_request.erl
Expand Up @@ -10,6 +10,8 @@
, raw_path/1
, query_str/1
, get_header/2
, get_arg_decoded/2
, get_arg_decoded/3
, get_arg/2
, get_arg/3
, get_args/1
Expand Down Expand Up @@ -64,6 +66,13 @@ get_arg(Key, #req{} = Req) ->
get_arg(Key, #req{args = Args}, Default) ->
proplists:get_value(Key, Args, Default).

get_arg_decoded(Key, #req{} = Req) ->
get_arg_decoded(Key, Req, undefined).

get_arg_decoded(Key, #req{args = Args}, Default) ->
EncodedValue = proplists:get_value(Key, Args, Default),
list_to_binary(http_uri:decode(binary_to_list(EncodedValue))).

%% @doc Parses application/x-www-form-urlencoded body into a proplist
body_qs(#req{body = Body} = Req) ->
case get_header(<<"Content-Type">>, Req) of
Expand Down
5 changes: 5 additions & 0 deletions test/elli_tests.erl
Expand Up @@ -19,6 +19,7 @@ elli_test_() ->
?_test(accept_content_type()),
?_test(user_connection()),
?_test(get_args()),
?_test(decoded_get_args()),
?_test(post_args()),
?_test(shorthand()),
?_test(too_many_headers()),
Expand Down Expand Up @@ -124,6 +125,10 @@ get_args() ->
{ok, Response} = httpc:request("http://localhost:3001/hello?name=knut"),
?assertEqual("Hello knut", body(Response)).

decoded_get_args() ->
{ok, Response} = httpc:request("http://localhost:3001/decoded-hello?name=knut%3D"),
?assertEqual("Hello knut=", body(Response)).

post_args() ->
Body = <<"name=foo&baz=quux">>,
ContentType = "application/x-www-form-urlencoded",
Expand Down

0 comments on commit 49cd96e

Please sign in to comment.