aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--include/http.hrl4
-rw-r--r--src/cowboy_http_req.erl41
2 files changed, 41 insertions, 4 deletions
diff --git a/include/http.hrl b/include/http.hrl
index ff41543..7e0380d 100644
--- a/include/http.hrl
+++ b/include/http.hrl
@@ -34,7 +34,7 @@
| 'Set-Cookie2' | 'X-Forwarded-For' | 'Cookie' | 'Keep-Alive'
| 'Proxy-Connection' | binary().
-type http_headers() :: list({http_header(), binary()}).
-%% -type http_cookies() :: term(). %% @todo
+-type http_cookies() :: list({binary(), binary()}).
-type http_status() :: non_neg_integer() | binary().
-record(http_req, {
@@ -58,7 +58,7 @@
raw_qs = undefined :: undefined | binary(),
bindings = undefined :: undefined | cowboy_dispatcher:bindings(),
headers = [] :: http_headers(),
-%% cookies = undefined :: undefined | http_cookies() %% @todo
+ cookies = undefined :: undefined | http_cookies(),
%% Request body.
body_state = waiting :: waiting | done,
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>