aboutsummaryrefslogtreecommitdiffstats
path: root/src/cowboy_http_req.erl
diff options
context:
space:
mode:
authorTom Burdick <[email protected]>2011-07-08 13:41:30 -0500
committerLoïc Hoguin <[email protected]>2011-07-26 13:53:31 +0200
commit5bd936db6606a27dfd91a0e2675889b58c212376 (patch)
tree7f7c76c82af50f6bb040293c569a39b5d88e8ffe /src/cowboy_http_req.erl
parenta29ccb070b0587a59f4266d0524b25a4efe98ccd (diff)
downloadcowboy-5bd936db6606a27dfd91a0e2675889b58c212376.tar.gz
cowboy-5bd936db6606a27dfd91a0e2675889b58c212376.tar.bz2
cowboy-5bd936db6606a27dfd91a0e2675889b58c212376.zip
Implement cookies in cowboy_http_req
Diffstat (limited to 'src/cowboy_http_req.erl')
-rw-r--r--src/cowboy_http_req.erl41
1 files changed, 39 insertions, 2 deletions
diff --git a/src/cowboy_http_req.erl b/src/cowboy_http_req.erl
index 60cdbc3..323f750 100644
--- a/src/cowboy_http_req.erl
+++ b/src/cowboy_http_req.erl
@@ -27,8 +27,8 @@
path/1, path_info/1, raw_path/1,
qs_val/2, qs_val/3, qs_vals/1, raw_qs/1,
binding/2, binding/3, bindings/1,
- header/2, header/3, headers/1
-%% cookie/2, cookie/3, cookies/1 @todo
+ header/2, header/3, headers/1,
+ cookie/2, cookie/3, cookies/1
]). %% Request API.
-export([
@@ -178,6 +178,43 @@ header(Name, Req, Default) when is_atom(Name) orelse is_binary(Name) ->
headers(Req) ->
{Req#http_req.headers, Req}.
+%% @equiv cookie(Name, Req, undefined)
+-spec cookie(binary(), #http_req{})
+ -> {binary() | true | undefined, #http_req{}}.
+cookie(Name, Req) ->
+ cookie(Name, Req, undefined).
+
+%% @doc Return the cookie value for the given key, or a default if
+%% missing.
+-spec cookie(binary(), #http_req{}, Default)
+ -> {binary() | true | Default, #http_req{}} when Default::any().
+cookie(Name, Req=#http_req{cookies=undefined}, Default) ->
+ case header('Cookie', Req) of
+ {undefined, Req2} ->
+ {Default, Req2#http_req{cookies=[]}};
+ {RawCookie, Req2} ->
+ Cookies = cowboy_cookies:parse_cookie(RawCookie),
+ cookie(Name, Req2#http_req{cookies=Cookies}, Default)
+ end;
+cookie(Name, Req, Default) ->
+ case lists:keyfind(Name, 1, Req#http_req.cookies) of
+ {Name, Value} -> {Value, Req};
+ false -> {Default, Req}
+ end.
+
+%% @doc Return the full list of cookie values.
+-spec cookies(#http_req{}) -> {list({binary(), binary() | true}), #http_req{}}.
+cookies(Req=#http_req{cookies=undefined}) ->
+ case header('Cookie', Req) of
+ {undefined, Req2} ->
+ {[], Req2#http_req{cookies=[]}};
+ {RawCookie, Req2} ->
+ Cookies = cowboy_cookies:parse_cookie(RawCookie),
+ cookies(Req2#http_req{cookies=Cookies})
+ end;
+cookies(Req=#http_req{cookies=Cookies}) ->
+ {Cookies, Req}.
+
%% Request Body API.
%% @doc Return the full body sent with the request, or <em>{error, badarg}</em>