0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 12:20:24 +00:00

Remove outdated comments, all edoc, plus a few minor tweaks

This commit is contained in:
Loïc Hoguin 2014-03-26 19:05:59 +01:00
parent 9110ee83fe
commit 17af50812c
20 changed files with 29 additions and 498 deletions

View file

@ -614,7 +614,8 @@ Response related exports
> >
> If a `Length` is provided, it will be sent in the > If a `Length` is provided, it will be sent in the
> content-length header in the response. It is recommended > content-length header in the response. It is recommended
> to set the length if it can be known in advance. > to set the length if it can be known in advance. Otherwise,
> the transfer-encoding header will be set to identity.
> >
> This function will only be called if the response is sent > This function will only be called if the response is sent
> using the `reply/2` or `reply/3` function. > using the `reply/2` or `reply/3` function.

View file

@ -12,7 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Convenience API to start and stop HTTP/HTTPS listeners.
-module(cowboy). -module(cowboy).
-export([start_http/4]). -export([start_http/4]).
@ -37,7 +36,6 @@
fun((http_status(), http_headers(), iodata(), Req) -> Req). fun((http_status(), http_headers(), iodata(), Req) -> Req).
-export_type([onresponse_fun/0]). -export_type([onresponse_fun/0]).
%% @doc Start an HTTP listener.
-spec start_http(ranch:ref(), non_neg_integer(), ranch_tcp:opts(), -spec start_http(ranch:ref(), non_neg_integer(), ranch_tcp:opts(),
cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}. cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}.
start_http(Ref, NbAcceptors, TransOpts, ProtoOpts) start_http(Ref, NbAcceptors, TransOpts, ProtoOpts)
@ -45,7 +43,6 @@ start_http(Ref, NbAcceptors, TransOpts, ProtoOpts)
ranch:start_listener(Ref, NbAcceptors, ranch:start_listener(Ref, NbAcceptors,
ranch_tcp, TransOpts, cowboy_protocol, ProtoOpts). ranch_tcp, TransOpts, cowboy_protocol, ProtoOpts).
%% @doc Start an HTTPS listener.
-spec start_https(ranch:ref(), non_neg_integer(), ranch_ssl:opts(), -spec start_https(ranch:ref(), non_neg_integer(), ranch_ssl:opts(),
cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}. cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}.
start_https(Ref, NbAcceptors, TransOpts, ProtoOpts) start_https(Ref, NbAcceptors, TransOpts, ProtoOpts)
@ -53,7 +50,6 @@ start_https(Ref, NbAcceptors, TransOpts, ProtoOpts)
ranch:start_listener(Ref, NbAcceptors, ranch:start_listener(Ref, NbAcceptors,
ranch_ssl, TransOpts, cowboy_protocol, ProtoOpts). ranch_ssl, TransOpts, cowboy_protocol, ProtoOpts).
%% @doc Start a SPDY listener.
-spec start_spdy(ranch:ref(), non_neg_integer(), ranch_ssl:opts(), -spec start_spdy(ranch:ref(), non_neg_integer(), ranch_ssl:opts(),
cowboy_spdy:opts()) -> {ok, pid()} | {error, any()}. cowboy_spdy:opts()) -> {ok, pid()} | {error, any()}.
start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts) start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts)
@ -66,20 +62,14 @@ start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts)
ranch:start_listener(Ref, NbAcceptors, ranch:start_listener(Ref, NbAcceptors,
ranch_ssl, TransOpts2, cowboy_spdy, ProtoOpts). ranch_ssl, TransOpts2, cowboy_spdy, ProtoOpts).
%% @doc Stop a listener.
-spec stop_listener(ranch:ref()) -> ok | {error, not_found}. -spec stop_listener(ranch:ref()) -> ok | {error, not_found}.
stop_listener(Ref) -> stop_listener(Ref) ->
ranch:stop_listener(Ref). ranch:stop_listener(Ref).
%% @doc Convenience function for setting an environment value.
%%
%% Allows you to update live an environment value used by middlewares.
%% This function is primarily intended to simplify updating the dispatch
%% list used for routing.
-spec set_env(ranch:ref(), atom(), any()) -> ok. -spec set_env(ranch:ref(), atom(), any()) -> ok.
set_env(Ref, Name, Value) -> set_env(Ref, Name, Value) ->
Opts = ranch:get_protocol_options(Ref), Opts = ranch:get_protocol_options(Ref),
{_, Env} = lists:keyfind(env, 1, Opts), {_, Env} = lists:keyfind(env, 1, Opts),
Env2 = [{Name, Value}|lists:keydelete(Name, 1, Env)], Opts2 = lists:keyreplace(env, 1, Opts,
Opts2 = lists:keyreplace(env, 1, Opts, {env, Env2}), {env, lists:keystore(Name, 1, Env, {Name, Value})}),
ok = ranch:set_protocol_options(Ref, Opts2). ok = ranch:set_protocol_options(Ref, Opts2).

View file

@ -12,16 +12,12 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @private
-module(cowboy_app). -module(cowboy_app).
-behaviour(application). -behaviour(application).
%% API.
-export([start/2]). -export([start/2]).
-export([stop/1]). -export([stop/1]).
%% API.
start(_Type, _Args) -> start(_Type, _Args) ->
cowboy_sup:start_link(). cowboy_sup:start_link().

View file

@ -12,7 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Binary string manipulation.
-module(cowboy_bstr). -module(cowboy_bstr).
%% Binary strings. %% Binary strings.
@ -24,11 +23,9 @@
-export([char_to_lower/1]). -export([char_to_lower/1]).
-export([char_to_upper/1]). -export([char_to_upper/1]).
%% @doc Capitalize a token.
%%
%% The first letter and all letters after a dash are capitalized. %% The first letter and all letters after a dash are capitalized.
%% This is the form seen for header names in the HTTP/1.1 RFC and %% This is the form seen for header names in the HTTP/1.1 RFC and
%% others. Note that using this form isn't required, as header name %% others. Note that using this form isn't required, as header names
%% are case insensitive, and it is only provided for use with eventual %% are case insensitive, and it is only provided for use with eventual
%% badly implemented clients. %% badly implemented clients.
-spec capitalize_token(B) -> B when B::binary(). -spec capitalize_token(B) -> B when B::binary().
@ -43,19 +40,14 @@ capitalize_token(<< C, Rest/bits >>, true, Acc) ->
capitalize_token(<< C, Rest/bits >>, false, Acc) -> capitalize_token(<< C, Rest/bits >>, false, Acc) ->
capitalize_token(Rest, false, << Acc/binary, (char_to_lower(C)) >>). capitalize_token(Rest, false, << Acc/binary, (char_to_lower(C)) >>).
%% @doc Convert a binary string to lowercase.
-spec to_lower(B) -> B when B::binary(). -spec to_lower(B) -> B when B::binary().
to_lower(B) -> to_lower(B) ->
<< << (char_to_lower(C)) >> || << C >> <= B >>. << << (char_to_lower(C)) >> || << C >> <= B >>.
%% @doc Convert a binary string to uppercase.
-spec to_upper(B) -> B when B::binary(). -spec to_upper(B) -> B when B::binary().
to_upper(B) -> to_upper(B) ->
<< << (char_to_upper(C)) >> || << C >> <= B >>. << << (char_to_upper(C)) >> || << C >> <= B >>.
%% @doc Convert [A-Z] characters to lowercase.
%% @end
%% We gain noticeable speed by matching each value directly.
-spec char_to_lower(char()) -> char(). -spec char_to_lower(char()) -> char().
char_to_lower($A) -> $a; char_to_lower($A) -> $a;
char_to_lower($B) -> $b; char_to_lower($B) -> $b;
@ -85,7 +77,6 @@ char_to_lower($Y) -> $y;
char_to_lower($Z) -> $z; char_to_lower($Z) -> $z;
char_to_lower(Ch) -> Ch. char_to_lower(Ch) -> Ch.
%% @doc Convert [a-z] characters to uppercase.
-spec char_to_upper(char()) -> char(). -spec char_to_upper(char()) -> char().
char_to_upper($a) -> $A; char_to_upper($a) -> $A;
char_to_upper($b) -> $B; char_to_upper($b) -> $B;
@ -118,9 +109,7 @@ char_to_upper(Ch) -> Ch.
%% Tests. %% Tests.
-ifdef(TEST). -ifdef(TEST).
capitalize_token_test_() -> capitalize_token_test_() ->
%% {Header, Result}
Tests = [ Tests = [
{<<"heLLo-woRld">>, <<"Hello-World">>}, {<<"heLLo-woRld">>, <<"Hello-World">>},
{<<"Sec-Websocket-Version">>, <<"Sec-Websocket-Version">>}, {<<"Sec-Websocket-Version">>, <<"Sec-Websocket-Version">>},
@ -131,5 +120,4 @@ capitalize_token_test_() ->
{<<"Sec-WebSocket---Version">>, <<"Sec-Websocket---Version">>} {<<"Sec-WebSocket---Version">>, <<"Sec-Websocket---Version">>}
], ],
[{H, fun() -> R = capitalize_token(H) end} || {H, R} <- Tests]. [{H, fun() -> R = capitalize_token(H) end} || {H, R} <- Tests].
-endif. -endif.

View file

@ -12,8 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Date and time related functions.
%%
%% While a gen_server process runs in the background to update %% While a gen_server process runs in the background to update
%% the cache of formatted dates every second, all API calls are %% the cache of formatted dates every second, all API calls are
%% local and directly read from the ETS cache table, providing %% local and directly read from the ETS cache table, providing
@ -41,68 +39,55 @@
tref = undefined :: undefined | timer:tref() tref = undefined :: undefined | timer:tref()
}). }).
-define(SERVER, ?MODULE).
-define(TABLE, ?MODULE).
%% API. %% API.
%% @private
-spec start_link() -> {ok, pid()}. -spec start_link() -> {ok, pid()}.
start_link() -> start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
%% @private
-spec stop() -> stopped. -spec stop() -> stopped.
stop() -> stop() ->
gen_server:call(?SERVER, stop). gen_server:call(?MODULE, stop).
%% @doc Return the current date and time formatted according to RFC-1123.
-spec rfc1123() -> binary(). -spec rfc1123() -> binary().
rfc1123() -> rfc1123() ->
ets:lookup_element(?TABLE, rfc1123, 2). ets:lookup_element(?MODULE, rfc1123, 2).
%% @doc Return the given date and time formatted according to RFC-1123.
-spec rfc1123(calendar:datetime()) -> binary(). -spec rfc1123(calendar:datetime()) -> binary().
rfc1123(DateTime) -> rfc1123(DateTime) ->
update_rfc1123(<<>>, undefined, DateTime). update_rfc1123(<<>>, undefined, DateTime).
%% gen_server. %% gen_server.
%% @private
init([]) -> init([]) ->
?TABLE = ets:new(?TABLE, [set, protected, ?MODULE = ets:new(?MODULE, [set, protected,
named_table, {read_concurrency, true}]), named_table, {read_concurrency, true}]),
T = erlang:universaltime(), T = erlang:universaltime(),
B = update_rfc1123(<<>>, undefined, T), B = update_rfc1123(<<>>, undefined, T),
{ok, TRef} = timer:send_interval(1000, update), {ok, TRef} = timer:send_interval(1000, update),
ets:insert(?TABLE, {rfc1123, B}), ets:insert(?MODULE, {rfc1123, B}),
{ok, #state{universaltime=T, rfc1123=B, tref=TRef}}. {ok, #state{universaltime=T, rfc1123=B, tref=TRef}}.
%% @private
handle_call(stop, _From, State=#state{tref=TRef}) -> handle_call(stop, _From, State=#state{tref=TRef}) ->
{ok, cancel} = timer:cancel(TRef), {ok, cancel} = timer:cancel(TRef),
{stop, normal, stopped, State}; {stop, normal, stopped, State};
handle_call(_Request, _From, State) -> handle_call(_Request, _From, State) ->
{reply, ignored, State}. {reply, ignored, State}.
%% @private
handle_cast(_Msg, State) -> handle_cast(_Msg, State) ->
{noreply, State}. {noreply, State}.
%% @private
handle_info(update, #state{universaltime=Prev, rfc1123=B1, tref=TRef}) -> handle_info(update, #state{universaltime=Prev, rfc1123=B1, tref=TRef}) ->
T = erlang:universaltime(), T = erlang:universaltime(),
B2 = update_rfc1123(B1, Prev, T), B2 = update_rfc1123(B1, Prev, T),
ets:insert(?TABLE, {rfc1123, B2}), ets:insert(?MODULE, {rfc1123, B2}),
{noreply, #state{universaltime=T, rfc1123=B2, tref=TRef}}; {noreply, #state{universaltime=T, rfc1123=B2, tref=TRef}};
handle_info(_Info, State) -> handle_info(_Info, State) ->
{noreply, State}. {noreply, State}.
%% @private
terminate(_Reason, _State) -> terminate(_Reason, _State) ->
ok. ok.
%% @private
code_change(_OldVsn, State, _Extra) -> code_change(_OldVsn, State, _Extra) ->
{ok, State}. {ok, State}.
@ -174,7 +159,6 @@ month(12) -> <<"Dec">>.
%% Tests. %% Tests.
-ifdef(TEST). -ifdef(TEST).
update_rfc1123_test_() -> update_rfc1123_test_() ->
Tests = [ Tests = [
{<<"Sat, 14 May 2011 14:25:33 GMT">>, undefined, {<<"Sat, 14 May 2011 14:25:33 GMT">>, undefined,
@ -215,5 +199,4 @@ pad_int_test_() ->
{56, <<"56">>}, {57, <<"57">>}, {58, <<"58">>}, {59, <<"59">>} {56, <<"56">>}, {57, <<"57">>}, {58, <<"58">>}, {59, <<"59">>}
], ],
[{I, fun() -> O = pad_int(I) end} || {I, O} <- Tests]. [{I, fun() -> O = pad_int(I) end} || {I, O} <- Tests].
-endif. -endif.

View file

@ -12,7 +12,7 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Handler middleware. %% Handler middleware.
%% %%
%% Execute the handler given by the <em>handler</em> and <em>handler_opts</em> %% Execute the handler given by the <em>handler</em> and <em>handler_opts</em>
%% environment values. The result of this execution is added to the %% environment values. The result of this execution is added to the
@ -27,8 +27,6 @@
%% by default. This can be configured through the <em>loop_max_buffer</em> %% by default. This can be configured through the <em>loop_max_buffer</em>
%% environment value. The request will be terminated with an %% environment value. The request will be terminated with an
%% <em>{error, overflow}</em> reason if this threshold is reached. %% <em>{error, overflow}</em> reason if this threshold is reached.
%%
%% @see cowboy_http_handler
-module(cowboy_handler). -module(cowboy_handler).
-behaviour(cowboy_middleware). -behaviour(cowboy_middleware).
@ -45,7 +43,6 @@
resp_sent = false :: boolean() resp_sent = false :: boolean()
}). }).
%% @private
-spec execute(Req, Env) -spec execute(Req, Env)
-> {ok, Req, Env} | {error, 500, Req} -> {ok, Req, Env} | {error, 500, Req}
| {suspend, ?MODULE, handler_loop, [any()]} | {suspend, ?MODULE, handler_loop, [any()]}
@ -148,8 +145,6 @@ handler_after_callback(Req, State=#state{resp_sent=false}, Handler,
handler_after_callback(Req, State, Handler, HandlerState) -> handler_after_callback(Req, State, Handler, HandlerState) ->
handler_before_loop(Req, State, Handler, HandlerState). handler_before_loop(Req, State, Handler, HandlerState).
%% We don't listen for Transport closes because that would force us
%% to receive data and buffer it indefinitely.
-spec handler_before_loop(Req, #state{}, module(), any()) -spec handler_before_loop(Req, #state{}, module(), any())
-> {ok, Req, cowboy_middleware:env()} -> {ok, Req, cowboy_middleware:env()}
| {error, 500, Req} | {suspend, module(), atom(), [any()]} | {error, 500, Req} | {suspend, module(), atom(), [any()]}
@ -177,7 +172,6 @@ handler_loop_timeout(State=#state{loop_timeout=Timeout,
TRef = erlang:start_timer(Timeout, self(), ?MODULE), TRef = erlang:start_timer(Timeout, self(), ?MODULE),
State#state{loop_timeout_ref=TRef}. State#state{loop_timeout_ref=TRef}.
%% @private
-spec handler_loop(Req, #state{}, module(), any()) -spec handler_loop(Req, #state{}, module(), any())
-> {ok, Req, cowboy_middleware:env()} -> {ok, Req, cowboy_middleware:env()}
| {error, 500, Req} | {suspend, module(), atom(), [any()]} | {error, 500, Req} | {suspend, module(), atom(), [any()]}

View file

@ -13,7 +13,7 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Core HTTP parsing API. %% Deprecated HTTP parsing API.
-module(cowboy_http). -module(cowboy_http).
%% Parsing. %% Parsing.
@ -44,7 +44,6 @@
%% Parsing. %% Parsing.
%% @doc Parse a non-empty list of the given type.
-spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}. -spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}.
nonempty_list(Data, Fun) -> nonempty_list(Data, Fun) ->
case list(Data, Fun, []) of case list(Data, Fun, []) of
@ -53,7 +52,6 @@ nonempty_list(Data, Fun) ->
L -> lists:reverse(L) L -> lists:reverse(L)
end. end.
%% @doc Parse a list of the given type.
-spec list(binary(), fun()) -> list() | {error, badarg}. -spec list(binary(), fun()) -> list() | {error, badarg}.
list(Data, Fun) -> list(Data, Fun) ->
case list(Data, Fun, []) of case list(Data, Fun, []) of
@ -81,8 +79,6 @@ list(Data, Fun, Acc) ->
end) end)
end). end).
%% @doc Parse a content type.
%%
%% We lowercase the charset header as we know it's case insensitive. %% We lowercase the charset header as we know it's case insensitive.
-spec content_type(binary()) -> any(). -spec content_type(binary()) -> any().
content_type(Data) -> content_type(Data) ->
@ -104,7 +100,6 @@ content_type(Data) ->
end) end)
end). end).
%% @doc Parse a media range.
-spec media_range(binary(), fun()) -> any(). -spec media_range(binary(), fun()) -> any().
media_range(Data, Fun) -> media_range(Data, Fun) ->
media_type(Data, media_type(Data,
@ -147,7 +142,6 @@ media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) ->
Type, SubType, [{Attr, Value}|Acc]) Type, SubType, [{Attr, Value}|Acc])
end). end).
%% @doc Parse a media type.
-spec media_type(binary(), fun()) -> any(). -spec media_type(binary(), fun()) -> any().
media_type(Data, Fun) -> media_type(Data, Fun) ->
token_ci(Data, token_ci(Data,
@ -207,8 +201,6 @@ accept_ext_value(Data, Fun, Type, SubType, Params, Quality, Acc, Attr) ->
Type, SubType, Params, Quality, [{Attr, Value}|Acc]) Type, SubType, Params, Quality, [{Attr, Value}|Acc])
end). end).
%% @doc Parse a conneg header (Accept-Charset, Accept-Encoding),
%% followed by an optional quality value.
-spec conneg(binary(), fun()) -> any(). -spec conneg(binary(), fun()) -> any().
conneg(Data, Fun) -> conneg(Data, Fun) ->
token_ci(Data, token_ci(Data,
@ -220,7 +212,6 @@ conneg(Data, Fun) ->
end) end)
end). end).
%% @doc Parse a language range, followed by an optional quality value.
-spec language_range(binary(), fun()) -> any(). -spec language_range(binary(), fun()) -> any().
language_range(<< $*, Rest/binary >>, Fun) -> language_range(<< $*, Rest/binary >>, Fun) ->
language_range_ret(Rest, Fun, '*'); language_range_ret(Rest, Fun, '*');
@ -281,12 +272,10 @@ maybe_qparam(Data, Fun) ->
Fun(Rest, 1000) Fun(Rest, 1000)
end). end).
%% @doc Parse a quality parameter string (for example q=0.500).
-spec qparam(binary(), fun()) -> any(). -spec qparam(binary(), fun()) -> any().
qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q -> qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q ->
qvalue(Data, Fun). qvalue(Data, Fun).
%% @doc Parse either a list of entity tags or a "*".
-spec entity_tag_match(binary()) -> any(). -spec entity_tag_match(binary()) -> any().
entity_tag_match(<< $*, Rest/binary >>) -> entity_tag_match(<< $*, Rest/binary >>) ->
whitespace(Rest, whitespace(Rest,
@ -296,7 +285,6 @@ entity_tag_match(<< $*, Rest/binary >>) ->
entity_tag_match(Data) -> entity_tag_match(Data) ->
nonempty_list(Data, fun entity_tag/2). nonempty_list(Data, fun entity_tag/2).
%% @doc Parse an entity-tag.
-spec entity_tag(binary(), fun()) -> any(). -spec entity_tag(binary(), fun()) -> any().
entity_tag(<< "W/", Rest/binary >>, Fun) -> entity_tag(<< "W/", Rest/binary >>, Fun) ->
opaque_tag(Rest, Fun, weak); opaque_tag(Rest, Fun, weak);
@ -310,7 +298,6 @@ opaque_tag(Data, Fun, Strength) ->
(Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag}) (Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag})
end). end).
%% @doc Parse an expectation.
-spec expectation(binary(), fun()) -> any(). -spec expectation(binary(), fun()) -> any().
expectation(Data, Fun) -> expectation(Data, Fun) ->
token_ci(Data, token_ci(Data,
@ -326,7 +313,6 @@ expectation(Data, Fun) ->
Fun(Rest, Expectation) Fun(Rest, Expectation)
end). end).
%% @doc Parse a list of parameters (a=b;c=d).
-spec params(binary(), fun()) -> any(). -spec params(binary(), fun()) -> any().
params(Data, Fun) -> params(Data, Fun) ->
params(Data, Fun, []). params(Data, Fun, []).
@ -358,9 +344,6 @@ param(Data, Fun) ->
end) end)
end). end).
%% @doc Parse an HTTP date (RFC1123, RFC850 or asctime date).
%% @end
%%
%% While this may not be the most efficient date parsing we can do, %% While this may not be the most efficient date parsing we can do,
%% it should work fine for our purposes because all HTTP dates should %% it should work fine for our purposes because all HTTP dates should
%% be sent as RFC1123 dates in HTTP/1.1. %% be sent as RFC1123 dates in HTTP/1.1.
@ -383,7 +366,6 @@ http_date(Data) ->
HTTPDate HTTPDate
end. end.
%% @doc Parse an RFC1123 date.
-spec rfc1123_date(binary()) -> any(). -spec rfc1123_date(binary()) -> any().
rfc1123_date(Data) -> rfc1123_date(Data) ->
wkday(Data, wkday(Data,
@ -403,7 +385,6 @@ rfc1123_date(Data) ->
{error, badarg} {error, badarg}
end). end).
%% @doc Parse an RFC850 date.
-spec rfc850_date(binary()) -> any(). -spec rfc850_date(binary()) -> any().
%% From the RFC: %% From the RFC:
%% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date %% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
@ -427,7 +408,6 @@ rfc850_date(Data) ->
{error, badarg} {error, badarg}
end). end).
%% @doc Parse an asctime date.
-spec asctime_date(binary()) -> any(). -spec asctime_date(binary()) -> any().
asctime_date(Data) -> asctime_date(Data) ->
wkday(Data, wkday(Data,
@ -586,7 +566,6 @@ time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun)
{error, badarg} {error, badarg}
end. end.
%% @doc Skip whitespace.
-spec whitespace(binary(), fun()) -> any(). -spec whitespace(binary(), fun()) -> any().
whitespace(<< C, Rest/binary >>, Fun) whitespace(<< C, Rest/binary >>, Fun)
when C =:= $\s; C =:= $\t -> when C =:= $\s; C =:= $\t ->
@ -594,7 +573,6 @@ whitespace(<< C, Rest/binary >>, Fun)
whitespace(Data, Fun) -> whitespace(Data, Fun) ->
Fun(Data). Fun(Data).
%% @doc Parse a list of digits as a non negative integer.
-spec digits(binary()) -> non_neg_integer() | {error, badarg}. -spec digits(binary()) -> non_neg_integer() | {error, badarg}.
digits(Data) -> digits(Data) ->
digits(Data, digits(Data,
@ -621,8 +599,6 @@ digits(<< C, Rest/binary >>, Fun, Acc)
digits(Data, Fun, Acc) -> digits(Data, Fun, Acc) ->
Fun(Data, Acc). Fun(Data, Acc).
%% @doc Parse a list of case-insensitive alpha characters.
%%
%% Changes all characters to lowercase. %% Changes all characters to lowercase.
-spec alpha(binary(), fun()) -> any(). -spec alpha(binary(), fun()) -> any().
alpha(Data, Fun) -> alpha(Data, Fun) ->
@ -639,7 +615,6 @@ alpha(<< C, Rest/binary >>, Fun, Acc)
alpha(Data, Fun, Acc) -> alpha(Data, Fun, Acc) ->
Fun(Data, Acc). Fun(Data, Acc).
%% @doc Parse either a token or a quoted string.
-spec word(binary(), fun()) -> any(). -spec word(binary(), fun()) -> any().
word(Data = << $", _/binary >>, Fun) -> word(Data = << $", _/binary >>, Fun) ->
quoted_string(Data, Fun); quoted_string(Data, Fun);
@ -649,14 +624,11 @@ word(Data, Fun) ->
(Rest, Token) -> Fun(Rest, Token) (Rest, Token) -> Fun(Rest, Token)
end). end).
%% @doc Parse a case-insensitive token.
%%
%% Changes all characters to lowercase. %% Changes all characters to lowercase.
-spec token_ci(binary(), fun()) -> any(). -spec token_ci(binary(), fun()) -> any().
token_ci(Data, Fun) -> token_ci(Data, Fun) ->
token(Data, Fun, ci, <<>>). token(Data, Fun, ci, <<>>).
%% @doc Parse a token.
-spec token(binary(), fun()) -> any(). -spec token(binary(), fun()) -> any().
token(Data, Fun) -> token(Data, Fun) ->
token(Data, Fun, cs, <<>>). token(Data, Fun, cs, <<>>).
@ -677,7 +649,6 @@ token(<< C, Rest/binary >>, Fun, Case = ci, Acc) ->
token(<< C, Rest/binary >>, Fun, Case, Acc) -> token(<< C, Rest/binary >>, Fun, Case, Acc) ->
token(Rest, Fun, Case, << Acc/binary, C >>). token(Rest, Fun, Case, << Acc/binary, C >>).
%% @doc Parse a quoted string.
-spec quoted_string(binary(), fun()) -> any(). -spec quoted_string(binary(), fun()) -> any().
quoted_string(<< $", Rest/binary >>, Fun) -> quoted_string(<< $", Rest/binary >>, Fun) ->
quoted_string(Rest, Fun, <<>>). quoted_string(Rest, Fun, <<>>).
@ -692,7 +663,6 @@ quoted_string(<< $\\, C, Rest/binary >>, Fun, Acc) ->
quoted_string(<< C, Rest/binary >>, Fun, Acc) -> quoted_string(<< C, Rest/binary >>, Fun, Acc) ->
quoted_string(Rest, Fun, << Acc/binary, C >>). quoted_string(Rest, Fun, << Acc/binary, C >>).
%% @doc Parse a quality value.
-spec qvalue(binary(), fun()) -> any(). -spec qvalue(binary(), fun()) -> any().
qvalue(<< $0, $., Rest/binary >>, Fun) -> qvalue(<< $0, $., Rest/binary >>, Fun) ->
qvalue(Rest, Fun, 0, 100); qvalue(Rest, Fun, 0, 100);
@ -721,8 +691,7 @@ qvalue(<< C, Rest/binary >>, Fun, Q, M)
qvalue(Data, Fun, Q, _M) -> qvalue(Data, Fun, Q, _M) ->
Fun(Data, Q). Fun(Data, Q).
%% @doc Parse authorization value according rfc 2617. %% Only RFC2617 Basic authorization is supported so far.
%% Only Basic authorization is supported so far.
-spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}. -spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}.
authorization(UserPass, Type = <<"basic">>) -> authorization(UserPass, Type = <<"basic">>) ->
whitespace(UserPass, whitespace(UserPass,
@ -738,7 +707,6 @@ authorization(UserPass, Type = <<"basic">>) ->
authorization(String, Type) -> authorization(String, Type) ->
whitespace(String, fun(Rest) -> {Type, Rest} end). whitespace(String, fun(Rest) -> {Type, Rest} end).
%% @doc Parse user credentials.
-spec authorization_basic_userid(binary(), fun()) -> any(). -spec authorization_basic_userid(binary(), fun()) -> any().
authorization_basic_userid(Data, Fun) -> authorization_basic_userid(Data, Fun) ->
authorization_basic_userid(Data, Fun, <<>>). authorization_basic_userid(Data, Fun, <<>>).
@ -767,7 +735,6 @@ authorization_basic_password(<<>>, Fun, Acc) ->
authorization_basic_password(<<C, Rest/binary>>, Fun, Acc) -> authorization_basic_password(<<C, Rest/binary>>, Fun, Acc) ->
authorization_basic_password(Rest, Fun, <<Acc/binary, C>>). authorization_basic_password(Rest, Fun, <<Acc/binary, C>>).
%% @doc Parse range header according rfc 2616.
-spec range(binary()) -> {Unit, [Range]} | {error, badarg} when -spec range(binary()) -> {Unit, [Range]} | {error, badarg} when
Unit :: binary(), Unit :: binary(),
Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer(). Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer().
@ -825,7 +792,6 @@ range_digits(Data, Default, Fun) ->
Fun(Data, Default) Fun(Data, Default)
end). end).
%% @doc Parse a non empty list of tokens followed with optional parameters.
-spec parameterized_tokens(binary()) -> any(). -spec parameterized_tokens(binary()) -> any().
parameterized_tokens(Data) -> parameterized_tokens(Data) ->
nonempty_list(Data, nonempty_list(Data,
@ -870,7 +836,6 @@ parameterized_tokens_param(Data, Fun) ->
%% Decoding. %% Decoding.
%% @doc Decode an identity content.
%% @todo Move this to cowlib too I suppose. :-) %% @todo Move this to cowlib too I suppose. :-)
-spec ce_identity(binary()) -> {ok, binary()}. -spec ce_identity(binary()) -> {ok, binary()}.
ce_identity(Data) -> ce_identity(Data) ->
@ -879,9 +844,7 @@ ce_identity(Data) ->
%% Tests. %% Tests.
-ifdef(TEST). -ifdef(TEST).
nonempty_charset_list_test_() -> nonempty_charset_list_test_() ->
%% {Value, Result}
Tests = [ Tests = [
{<<>>, {error, badarg}}, {<<>>, {error, badarg}},
{<<"iso-8859-5, unicode-1-1;q=0.8">>, [ {<<"iso-8859-5, unicode-1-1;q=0.8">>, [
@ -898,7 +861,6 @@ nonempty_charset_list_test_() ->
[{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests]. [{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests].
nonempty_language_range_list_test_() -> nonempty_language_range_list_test_() ->
%% {Value, Result}
Tests = [ Tests = [
{<<"da, en-gb;q=0.8, en;q=0.7">>, [ {<<"da, en-gb;q=0.8, en;q=0.7">>, [
{<<"da">>, 1000}, {<<"da">>, 1000},
@ -917,7 +879,6 @@ nonempty_language_range_list_test_() ->
|| {V, R} <- Tests]. || {V, R} <- Tests].
nonempty_token_list_test_() -> nonempty_token_list_test_() ->
%% {Value, Result}
Tests = [ Tests = [
{<<>>, {error, badarg}}, {<<>>, {error, badarg}},
{<<" ">>, {error, badarg}}, {<<" ">>, {error, badarg}},
@ -933,7 +894,6 @@ nonempty_token_list_test_() ->
[{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests]. [{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
media_range_list_test_() -> media_range_list_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{<<"audio/*; q=0.2, audio/basic">>, [ {<<"audio/*; q=0.2, audio/basic">>, [
{{<<"audio">>, <<"*">>, []}, 200, []}, {{<<"audio">>, <<"*">>, []}, 200, []},
@ -978,7 +938,6 @@ media_range_list_test_() ->
[{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests]. [{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests].
entity_tag_match_test_() -> entity_tag_match_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]}, {<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]},
{<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>, {<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>,
@ -990,7 +949,6 @@ entity_tag_match_test_() ->
[{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests]. [{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests].
http_date_test_() -> http_date_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}, {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
{<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}, {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
@ -999,28 +957,24 @@ http_date_test_() ->
[{V, fun() -> R = http_date(V) end} || {V, R} <- Tests]. [{V, fun() -> R = http_date(V) end} || {V, R} <- Tests].
rfc1123_date_test_() -> rfc1123_date_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}} {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
], ],
[{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests]. [{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests].
rfc850_date_test_() -> rfc850_date_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}} {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
], ],
[{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests]. [{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests].
asctime_date_test_() -> asctime_date_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}} {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
], ],
[{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests]. [{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests].
content_type_test_() -> content_type_test_() ->
%% {ContentType, Result}
Tests = [ Tests = [
{<<"text/plain; charset=iso-8859-4">>, {<<"text/plain; charset=iso-8859-4">>,
{<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}}, {<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}},
@ -1037,7 +991,6 @@ content_type_test_() ->
[{V, fun () -> R = content_type(V) end} || {V, R} <- Tests]. [{V, fun () -> R = content_type(V) end} || {V, R} <- Tests].
parameterized_tokens_test_() -> parameterized_tokens_test_() ->
%% {ParameterizedTokens, Result}
Tests = [ Tests = [
{<<"foo">>, [{<<"foo">>, []}]}, {<<"foo">>, [{<<"foo">>, []}]},
{<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]}, {<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]},
@ -1048,7 +1001,6 @@ parameterized_tokens_test_() ->
[{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests]. [{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests].
digits_test_() -> digits_test_() ->
%% {Digits, Result}
Tests = [ Tests = [
{<<"42 ">>, 42}, {<<"42 ">>, 42},
{<<"69\t">>, 69}, {<<"69\t">>, 69},
@ -1093,5 +1045,4 @@ http_range_test_() ->
{error, badarg}} {error, badarg}}
], ],
[fun() -> R = range(V) end ||{V, R} <- Tests]. [fun() -> R = range(V) end ||{V, R} <- Tests].
-endif. -endif.

View file

@ -12,23 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Behaviour for short-lived HTTP handlers.
%%
%% <em>init/3</em> allows you to initialize a state for all subsequent
%% callbacks, and indicate to Cowboy whether you accept to handle the
%% request or want to shutdown without handling it, in which case the
%% <em>handle/2</em> call will simply be skipped.
%%
%% <em>handle/2</em> allows you to handle the request. It receives the
%% state previously defined.
%%
%% <em>terminate/3</em> allows you to clean up. It receives the
%% termination reason and the state previously defined.
%%
%% There is no required operation to perform in any of these callbacks
%% other than returning the proper values. Make sure you always return
%% the last modified Req so that Cowboy has the up to date information
%% about the request.
-module(cowboy_http_handler). -module(cowboy_http_handler).
-type opts() :: any(). -type opts() :: any().

View file

@ -12,29 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Behaviour for long-lived HTTP handlers.
%%
%% <em>init/3</em> allows you to initialize a state for all subsequent
%% callbacks, and indicate to Cowboy whether you accept to handle the
%% request or want to shutdown without handling it, in which case the
%% receive loop and <em>info/3</em> calls will simply be skipped.
%%
%% <em>info/3</em> allows you to handle the messages this process will
%% receive. It receives the message and the state previously defined.
%% It can decide to stop the receive loop or continue receiving.
%%
%% <em>terminate/3</em> allows you to clean up. It receives the
%% termination reason and the state previously defined.
%%
%% There is no required operation to perform in any of these callbacks
%% other than returning the proper values. Make sure you always return
%% the last modified Req so that Cowboy has the up to date information
%% about the request.
%%
%% It is recommended to use hibernate if this process is not going to
%% receive a lot of messages. It is also recommended to use a timeout
%% value so that the connection gets closed after a long period of
%% inactivity.
-module(cowboy_loop_handler). -module(cowboy_loop_handler).
-type opts() :: any(). -type opts() :: any().

View file

@ -12,17 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Behaviour for middlewares.
%%
%% Only one function needs to be implemented, <em>execute/2</em>.
%% It receives the Req and the environment and returns them
%% optionally modified. It can decide to stop the processing with
%% or without an error. It is also possible to hibernate the process
%% if needed.
%%
%% A middleware can perform any operation. Make sure you always return
%% the last modified Req so that Cowboy has the up to date information
%% about the request.
-module(cowboy_middleware). -module(cowboy_middleware).
-type env() :: [{atom(), any()}]. -type env() :: [{atom(), any()}].

View file

@ -13,39 +13,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc HTTP protocol handler.
%%
%% The available options are:
%% <dl>
%% <dt>compress</dt><dd>Whether to automatically compress the response
%% body when the conditions are met. Disabled by default.</dd>
%% <dt>env</dt><dd>The environment passed and optionally modified
%% by middlewares.</dd>
%% <dt>max_empty_lines</dt><dd>Max number of empty lines before a request.
%% Defaults to 5.</dd>
%% <dt>max_header_name_length</dt><dd>Max length allowed for header names.
%% Defaults to 64.</dd>
%% <dt>max_header_value_length</dt><dd>Max length allowed for header values.
%% Defaults to 4096.</dd>
%% <dt>max_headers</dt><dd>Max number of headers allowed.
%% Defaults to 100.</dd>
%% <dt>max_keepalive</dt><dd>Max number of requests allowed in a single
%% keep-alive session. Defaults to 100.</dd>
%% <dt>max_request_line_length</dt><dd>Max length allowed for the request
%% line. Defaults to 4096.</dd>
%% <dt>middlewares</dt><dd>The list of middlewares to execute when a
%% request is received.</dd>
%% <dt>onrequest</dt><dd>Optional fun that allows Req interaction before
%% any dispatching is done. Host info, path info and bindings are thus
%% not available at this point.</dd>
%% <dt>onresponse</dt><dd>Optional fun that allows replacing a response
%% sent by the application.</dd>
%% <dt>timeout</dt><dd>Time in milliseconds a client has to send the
%% full request line and headers. Defaults to 5000 milliseconds.</dd>
%% </dl>
%%
%% Note that there is no need to monitor these processes when using Cowboy as
%% an application as it already supervises them under the listener supervisor.
-module(cowboy_protocol). -module(cowboy_protocol).
%% API. %% API.
@ -93,7 +60,6 @@
%% API. %% API.
%% @doc Start an HTTP protocol process.
-spec start_link(ranch:ref(), inet:socket(), module(), opts()) -> {ok, pid()}. -spec start_link(ranch:ref(), inet:socket(), module(), opts()) -> {ok, pid()}.
start_link(Ref, Socket, Transport, Opts) -> start_link(Ref, Socket, Transport, Opts) ->
Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]), Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
@ -101,15 +67,13 @@ start_link(Ref, Socket, Transport, Opts) ->
%% Internal. %% Internal.
%% @doc Faster alternative to proplists:get_value/3. %% Faster alternative to proplists:get_value/3.
%% @private
get_value(Key, Opts, Default) -> get_value(Key, Opts, Default) ->
case lists:keyfind(Key, 1, Opts) of case lists:keyfind(Key, 1, Opts) of
{_, Value} -> Value; {_, Value} -> Value;
_ -> Default _ -> Default
end. end.
%% @private
-spec init(ranch:ref(), inet:socket(), module(), opts()) -> ok. -spec init(ranch:ref(), inet:socket(), module(), opts()) -> ok.
init(Ref, Socket, Transport, Opts) -> init(Ref, Socket, Transport, Opts) ->
Compress = get_value(compress, Opts, false), Compress = get_value(compress, Opts, false),
@ -172,7 +136,6 @@ wait_request(Buffer, State=#state{socket=Socket, transport=Transport,
terminate(State) terminate(State)
end. end.
%% @private
-spec parse_request(binary(), #state{}, non_neg_integer()) -> ok. -spec parse_request(binary(), #state{}, non_neg_integer()) -> ok.
%% Empty lines must be using \r\n. %% Empty lines must be using \r\n.
parse_request(<< $\n, _/binary >>, State, _) -> parse_request(<< $\n, _/binary >>, State, _) ->
@ -481,7 +444,6 @@ execute(Req, State, Env, [Middleware|Tail]) ->
error_terminate(Code, Req2, State) error_terminate(Code, Req2, State)
end. end.
%% @private
-spec resume(#state{}, cowboy_middleware:env(), [module()], -spec resume(#state{}, cowboy_middleware:env(), [module()],
module(), module(), [any()]) -> ok. module(), module(), [any()]) -> ok.
resume(State, Env, Tail, Module, Function, Args) -> resume(State, Env, Tail, Module, Function, Args) ->

View file

@ -13,31 +13,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc HTTP request manipulation API.
%%
%% The functions in this module try to follow this pattern for their
%% return types:
%% <dl>
%% <dt>access:</dt>
%% <dd><em>{Value, Req}</em></dd>
%% <dt>action:</dt>
%% <dd><em>{Result, Req} | {Result, Value, Req} | {error, atom()}</em></dd>
%% <dt>modification:</dt>
%% <dd><em>Req</em></dd>
%% <dt>question (<em>has_*</em> or <em>is_*</em>):</dt>
%% <dd><em>boolean()</em></dd>
%% </dl>
%%
%% Exceptions include <em>chunk/2</em> which always returns <em>'ok'</em>,
%% and <em>to_list/1</em> which returns a list of key/values.
%%
%% Also note that all body reading functions perform actions, as Cowboy
%% doesn't read the request body until they are called.
%%
%% Whenever <em>Req</em> is returned, it should always be kept in place of
%% the one given as argument in your function call, because it keeps
%% track of the request and response state. Doing so allows Cowboy to do
%% some lazy evaluation and cache results when possible.
-module(cowboy_req). -module(cowboy_req).
%% Request API. %% Request API.
@ -184,13 +159,6 @@
%% Request API. %% Request API.
%% @doc Create a new HTTP Req object.
%%
%% This function takes care of setting the owner's pid to self().
%% @private
%%
%% Since we always need to parse the Connection header, we do it
%% in an optimized way and add the parsed value to p_headers' cache.
-spec new(any(), module(), -spec new(any(), module(),
undefined | {inet:ip_address(), inet:port_number()}, undefined | {inet:ip_address(), inet:port_number()},
binary(), binary(), binary(), binary(), binary(), binary(),
@ -220,65 +188,51 @@ new(Socket, Transport, Peer, Method, Path, Query,
end end
end. end.
%% @doc Return the HTTP method of the request.
-spec method(Req) -> {binary(), Req} when Req::req(). -spec method(Req) -> {binary(), Req} when Req::req().
method(Req) -> method(Req) ->
{Req#http_req.method, Req}. {Req#http_req.method, Req}.
%% @doc Return the HTTP version used for the request.
-spec version(Req) -> {cowboy:http_version(), Req} when Req::req(). -spec version(Req) -> {cowboy:http_version(), Req} when Req::req().
version(Req) -> version(Req) ->
{Req#http_req.version, Req}. {Req#http_req.version, Req}.
%% @doc Return the peer address and port number of the remote host.
-spec peer(Req) -spec peer(Req)
-> {{inet:ip_address(), inet:port_number()}, Req} -> {{inet:ip_address(), inet:port_number()}, Req}
when Req::req(). when Req::req().
peer(Req) -> peer(Req) ->
{Req#http_req.peer, Req}. {Req#http_req.peer, Req}.
%% @doc Return the host binary string.
-spec host(Req) -> {binary(), Req} when Req::req(). -spec host(Req) -> {binary(), Req} when Req::req().
host(Req) -> host(Req) ->
{Req#http_req.host, Req}. {Req#http_req.host, Req}.
%% @doc Return the extra host information obtained from partially matching
%% the hostname using <em>'...'</em>.
-spec host_info(Req) -spec host_info(Req)
-> {cowboy_router:tokens() | undefined, Req} when Req::req(). -> {cowboy_router:tokens() | undefined, Req} when Req::req().
host_info(Req) -> host_info(Req) ->
{Req#http_req.host_info, Req}. {Req#http_req.host_info, Req}.
%% @doc Return the port used for this request.
-spec port(Req) -> {inet:port_number(), Req} when Req::req(). -spec port(Req) -> {inet:port_number(), Req} when Req::req().
port(Req) -> port(Req) ->
{Req#http_req.port, Req}. {Req#http_req.port, Req}.
%% @doc Return the path binary string.
-spec path(Req) -> {binary(), Req} when Req::req(). -spec path(Req) -> {binary(), Req} when Req::req().
path(Req) -> path(Req) ->
{Req#http_req.path, Req}. {Req#http_req.path, Req}.
%% @doc Return the extra path information obtained from partially matching
%% the patch using <em>'...'</em>.
-spec path_info(Req) -spec path_info(Req)
-> {cowboy_router:tokens() | undefined, Req} when Req::req(). -> {cowboy_router:tokens() | undefined, Req} when Req::req().
path_info(Req) -> path_info(Req) ->
{Req#http_req.path_info, Req}. {Req#http_req.path_info, Req}.
%% @doc Return the raw query string directly taken from the request.
-spec qs(Req) -> {binary(), Req} when Req::req(). -spec qs(Req) -> {binary(), Req} when Req::req().
qs(Req) -> qs(Req) ->
{Req#http_req.qs, Req}. {Req#http_req.qs, Req}.
%% @equiv qs_val(Name, Req, undefined)
-spec qs_val(binary(), Req) -spec qs_val(binary(), Req)
-> {binary() | true | undefined, Req} when Req::req(). -> {binary() | true | undefined, Req} when Req::req().
qs_val(Name, Req) when is_binary(Name) -> qs_val(Name, Req) when is_binary(Name) ->
qs_val(Name, Req, undefined). qs_val(Name, Req, undefined).
%% @doc Return the query string value for the given key, or a default if
%% missing.
-spec qs_val(binary(), Req, Default) -spec qs_val(binary(), Req, Default)
-> {binary() | true | Default, Req} when Req::req(), Default::any(). -> {binary() | true | Default, Req} when Req::req(), Default::any().
qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default) qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default)
@ -291,7 +245,6 @@ qs_val(Name, Req, Default) ->
false -> {Default, Req} false -> {Default, Req}
end. end.
%% @doc Return the full list of query string values.
-spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req(). -spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) -> qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) ->
QsVals = cow_qs:parse_qs(RawQs), QsVals = cow_qs:parse_qs(RawQs),
@ -299,10 +252,7 @@ qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) ->
qs_vals(Req=#http_req{qs_vals=QsVals}) -> qs_vals(Req=#http_req{qs_vals=QsVals}) ->
{QsVals, Req}. {QsVals, Req}.
%% @doc Return the request URL as a binary without the path and query string.
%%
%% The URL includes the scheme, host and port only. %% The URL includes the scheme, host and port only.
%% @see cowboy_req:url/1
-spec host_url(Req) -> {undefined | binary(), Req} when Req::req(). -spec host_url(Req) -> {undefined | binary(), Req} when Req::req().
host_url(Req=#http_req{port=undefined}) -> host_url(Req=#http_req{port=undefined}) ->
{undefined, Req}; {undefined, Req};
@ -319,8 +269,6 @@ host_url(Req=#http_req{transport=Transport, host=Host, port=Port}) ->
end, end,
{<< "http", Secure/binary, "://", Host/binary, PortBin/binary >>, Req}. {<< "http", Secure/binary, "://", Host/binary, PortBin/binary >>, Req}.
%% @doc Return the full request URL as a binary.
%%
%% The URL includes the scheme, host, port, path and query string. %% The URL includes the scheme, host, port, path and query string.
-spec url(Req) -> {undefined | binary(), Req} when Req::req(). -spec url(Req) -> {undefined | binary(), Req} when Req::req().
url(Req=#http_req{}) -> url(Req=#http_req{}) ->
@ -336,13 +284,10 @@ url(HostURL, Req=#http_req{path=Path, qs=QS}) ->
end, end,
{<< HostURL/binary, Path/binary, QS2/binary >>, Req}. {<< HostURL/binary, Path/binary, QS2/binary >>, Req}.
%% @equiv binding(Name, Req, undefined)
-spec binding(atom(), Req) -> {any() | undefined, Req} when Req::req(). -spec binding(atom(), Req) -> {any() | undefined, Req} when Req::req().
binding(Name, Req) when is_atom(Name) -> binding(Name, Req) when is_atom(Name) ->
binding(Name, Req, undefined). binding(Name, Req, undefined).
%% @doc Return the binding value for the given key obtained when matching
%% the host and path against the dispatch list, or a default if missing.
-spec binding(atom(), Req, Default) -spec binding(atom(), Req, Default)
-> {any() | Default, Req} when Req::req(), Default::any(). -> {any() | Default, Req} when Req::req(), Default::any().
binding(Name, Req, Default) when is_atom(Name) -> binding(Name, Req, Default) when is_atom(Name) ->
@ -351,18 +296,15 @@ binding(Name, Req, Default) when is_atom(Name) ->
false -> {Default, Req} false -> {Default, Req}
end. end.
%% @doc Return the full list of binding values.
-spec bindings(Req) -> {[{atom(), any()}], Req} when Req::req(). -spec bindings(Req) -> {[{atom(), any()}], Req} when Req::req().
bindings(Req) -> bindings(Req) ->
{Req#http_req.bindings, Req}. {Req#http_req.bindings, Req}.
%% @equiv header(Name, Req, undefined)
-spec header(binary(), Req) -spec header(binary(), Req)
-> {binary() | undefined, Req} when Req::req(). -> {binary() | undefined, Req} when Req::req().
header(Name, Req) -> header(Name, Req) ->
header(Name, Req, undefined). header(Name, Req, undefined).
%% @doc Return the header value for the given key, or a default if missing.
-spec header(binary(), Req, Default) -spec header(binary(), Req, Default)
-> {binary() | Default, Req} when Req::req(), Default::any(). -> {binary() | Default, Req} when Req::req(), Default::any().
header(Name, Req, Default) -> header(Name, Req, Default) ->
@ -371,16 +313,10 @@ header(Name, Req, Default) ->
false -> {Default, Req} false -> {Default, Req}
end. end.
%% @doc Return the full list of headers.
-spec headers(Req) -> {cowboy:http_headers(), Req} when Req::req(). -spec headers(Req) -> {cowboy:http_headers(), Req} when Req::req().
headers(Req) -> headers(Req) ->
{Req#http_req.headers, Req}. {Req#http_req.headers, Req}.
%% @doc Semantically parse headers.
%%
%% When the value isn't found, a proper default value for the type
%% returned is used as a return value.
%% @see parse_header/3
-spec parse_header(binary(), Req) -spec parse_header(binary(), Req)
-> {ok, any(), Req} | {undefined, binary(), Req} -> {ok, any(), Req} | {undefined, binary(), Req}
| {error, badarg} when Req::req(). | {error, badarg} when Req::req().
@ -390,14 +326,10 @@ parse_header(Name, Req=#http_req{p_headers=PHeaders}) ->
{Name, Value} -> {ok, Value, Req} {Name, Value} -> {ok, Value, Req}
end. end.
%% @doc Default values for semantic header parsing.
-spec parse_header_default(binary()) -> any(). -spec parse_header_default(binary()) -> any().
parse_header_default(<<"transfer-encoding">>) -> [<<"identity">>]; parse_header_default(<<"transfer-encoding">>) -> [<<"identity">>];
parse_header_default(_Name) -> undefined. parse_header_default(_Name) -> undefined.
%% @doc Semantically parse headers.
%%
%% When the header is unknown, the value is returned directly without parsing.
-spec parse_header(binary(), Req, any()) -spec parse_header(binary(), Req, any())
-> {ok, any(), Req} | {undefined, binary(), Req} -> {ok, any(), Req} | {undefined, binary(), Req}
| {error, badarg} when Req::req(). | {error, badarg} when Req::req().
@ -481,14 +413,11 @@ parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) ->
end end
end. end.
%% @equiv cookie(Name, Req, undefined)
-spec cookie(binary(), Req) -spec cookie(binary(), Req)
-> {binary() | undefined, Req} when Req::req(). -> {binary() | undefined, Req} when Req::req().
cookie(Name, Req) when is_binary(Name) -> cookie(Name, Req) when is_binary(Name) ->
cookie(Name, Req, undefined). cookie(Name, Req, undefined).
%% @doc Return the cookie value for the given key, or a default if
%% missing.
-spec cookie(binary(), Req, Default) -spec cookie(binary(), Req, Default)
-> {binary() | Default, Req} when Req::req(), Default::any(). -> {binary() | Default, Req} when Req::req(), Default::any().
cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) -> cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) ->
@ -504,7 +433,6 @@ cookie(Name, Req, Default) ->
false -> {Default, Req} false -> {Default, Req}
end. end.
%% @doc Return the full list of cookie values.
-spec cookies(Req) -> {list({binary(), binary()}), Req} when Req::req(). -spec cookies(Req) -> {list({binary(), binary()}), Req} when Req::req().
cookies(Req=#http_req{cookies=undefined}) -> cookies(Req=#http_req{cookies=undefined}) ->
case parse_header(<<"cookie">>, Req) of case parse_header(<<"cookie">>, Req) of
@ -519,16 +447,10 @@ cookies(Req=#http_req{cookies=undefined}) ->
cookies(Req=#http_req{cookies=Cookies}) -> cookies(Req=#http_req{cookies=Cookies}) ->
{Cookies, Req}. {Cookies, Req}.
%% @equiv meta(Name, Req, undefined)
-spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req(). -spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req().
meta(Name, Req) -> meta(Name, Req) ->
meta(Name, Req, undefined). meta(Name, Req, undefined).
%% @doc Return metadata information about the request.
%%
%% Metadata information varies from one protocol to another. Websockets
%% would define the protocol version here, while REST would use it to
%% indicate which media type, language and charset were retained.
-spec meta(atom(), Req, any()) -> {any(), Req} when Req::req(). -spec meta(atom(), Req, any()) -> {any(), Req} when Req::req().
meta(Name, Req, Default) -> meta(Name, Req, Default) ->
case lists:keyfind(Name, 1, Req#http_req.meta) of case lists:keyfind(Name, 1, Req#http_req.meta) of
@ -536,18 +458,12 @@ meta(Name, Req, Default) ->
false -> {Default, Req} false -> {Default, Req}
end. end.
%% @doc Set metadata information.
%%
%% You can use this function to attach information about the request.
%%
%% If the value already exists it will be overwritten.
-spec set_meta(atom(), any(), Req) -> Req when Req::req(). -spec set_meta(atom(), any(), Req) -> Req when Req::req().
set_meta(Name, Value, Req=#http_req{meta=Meta}) -> set_meta(Name, Value, Req=#http_req{meta=Meta}) ->
Req#http_req{meta=[{Name, Value}|lists:keydelete(Name, 1, Meta)]}. Req#http_req{meta=lists:keystore(Name, 1, Meta, {Name, Value})}.
%% Request Body API. %% Request Body API.
%% @doc Return whether the request message has a body.
-spec has_body(req()) -> boolean(). -spec has_body(req()) -> boolean().
has_body(Req) -> has_body(Req) ->
case lists:keyfind(<<"content-length">>, 1, Req#http_req.headers) of case lists:keyfind(<<"content-length">>, 1, Req#http_req.headers) of
@ -559,8 +475,6 @@ has_body(Req) ->
lists:keymember(<<"transfer-encoding">>, 1, Req#http_req.headers) lists:keymember(<<"transfer-encoding">>, 1, Req#http_req.headers)
end. end.
%% @doc Return the request message body length, if known.
%%
%% The length may not be known if Transfer-Encoding is not identity, %% The length may not be known if Transfer-Encoding is not identity,
%% and the body hasn't been read at the time of the call. %% and the body hasn't been read at the time of the call.
-spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req(). -spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req().
@ -573,12 +487,6 @@ body_length(Req) ->
{undefined, Req2} {undefined, Req2}
end. end.
%% @doc Initialize body streaming and set custom decoding functions.
%%
%% Calling this function is optional. It should only be used if you
%% need to override the default behavior of Cowboy. Otherwise you
%% should call stream_body/{1,2} directly.
%%
%% Two decodings happen. First a decoding function is applied to the %% Two decodings happen. First a decoding function is applied to the
%% transferred data, and then another is applied to the actual content. %% transferred data, and then another is applied to the actual content.
%% %%
@ -587,34 +495,17 @@ body_length(Req) ->
%% also initialized through this function. %% also initialized through this function.
%% %%
%% Content encoding is generally used for compression. %% Content encoding is generally used for compression.
%%
%% Standard encodings can be found in cowboy_http.
-spec init_stream(transfer_decode_fun(), any(), content_decode_fun(), Req) -spec init_stream(transfer_decode_fun(), any(), content_decode_fun(), Req)
-> {ok, Req} when Req::req(). -> {ok, Req} when Req::req().
init_stream(TransferDecode, TransferState, ContentDecode, Req) -> init_stream(TransferDecode, TransferState, ContentDecode, Req) ->
{ok, Req#http_req{body_state= {ok, Req#http_req{body_state=
{stream, 0, TransferDecode, TransferState, ContentDecode}}}. {stream, 0, TransferDecode, TransferState, ContentDecode}}}.
%% @equiv stream_body(1000000, Req)
-spec stream_body(Req) -> {ok, binary(), Req} -spec stream_body(Req) -> {ok, binary(), Req}
| {done, Req} | {error, atom()} when Req::req(). | {done, Req} | {error, atom()} when Req::req().
stream_body(Req) -> stream_body(Req) ->
stream_body(1000000, Req). stream_body(1000000, Req).
%% @doc Stream the request's body.
%%
%% This is the most low level function to read the request body.
%%
%% In most cases, if they weren't defined before using init_stream/4,
%% this function will guess which transfer and content encodings were
%% used for building the request body, and configure the decoding
%% functions that will be used when streaming.
%%
%% It then starts streaming the body, returning {ok, Data, Req}
%% for each streamed part, and {done, Req} when it's finished streaming.
%%
%% You can limit the size of the chunks being returned by using the
%% first argument which is the size in bytes. It defaults to 1000000 bytes.
-spec stream_body(non_neg_integer(), Req) -> {ok, binary(), Req} -spec stream_body(non_neg_integer(), Req) -> {ok, binary(), Req}
| {done, Req} | {error, atom()} when Req::req(). | {done, Req} | {error, atom()} when Req::req().
stream_body(MaxLength, Req=#http_req{body_state=waiting, version=Version, stream_body(MaxLength, Req=#http_req{body_state=waiting, version=Version,
@ -710,7 +601,6 @@ transfer_decode_done(Length, Rest, Req=#http_req{
Req#http_req{buffer=Rest, body_state=done, Req#http_req{buffer=Rest, body_state=done,
headers=Headers3, p_headers=PHeaders3}. headers=Headers3, p_headers=PHeaders3}.
%% @todo Probably needs a Rest.
-spec content_decode(content_decode_fun(), binary(), Req) -spec content_decode(content_decode_fun(), binary(), Req)
-> {ok, binary(), Req} | {error, atom()} when Req::req(). -> {ok, binary(), Req} | {error, atom()} when Req::req().
content_decode(ContentDecode, Data, Req) -> content_decode(ContentDecode, Data, Req) ->
@ -719,12 +609,10 @@ content_decode(ContentDecode, Data, Req) ->
{error, Reason} -> {error, Reason} {error, Reason} -> {error, Reason}
end. end.
%% @equiv body(8000000, Req)
-spec body(Req) -> {ok, binary(), Req} | {error, atom()} when Req::req(). -spec body(Req) -> {ok, binary(), Req} | {error, atom()} when Req::req().
body(Req) -> body(Req) ->
body(8000000, Req). body(8000000, Req).
%% @doc Return the body sent with the request.
-spec body(non_neg_integer() | infinity, Req) -spec body(non_neg_integer() | infinity, Req)
-> {ok, binary(), Req} | {error, atom()} when Req::req(). -> {ok, binary(), Req} | {error, atom()} when Req::req().
body(MaxBodyLength, Req) -> body(MaxBodyLength, Req) ->
@ -760,15 +648,12 @@ skip_body(Req) ->
{error, Reason} -> {error, Reason} {error, Reason} -> {error, Reason}
end. end.
%% @equiv body_qs(16000, Req)
-spec body_qs(Req) -spec body_qs(Req)
-> {ok, [{binary(), binary() | true}], Req} | {error, atom()} -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
when Req::req(). when Req::req().
body_qs(Req) -> body_qs(Req) ->
body_qs(16000, Req). body_qs(16000, Req).
%% @doc Return the body sent with the request, parsed as an
%% application/x-www-form-urlencoded string.
%% Essentially a POST query string. %% Essentially a POST query string.
-spec body_qs(non_neg_integer() | infinity, Req) -spec body_qs(non_neg_integer() | infinity, Req)
-> {ok, [{binary(), binary() | true}], Req} | {error, atom()} -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
@ -783,7 +668,6 @@ body_qs(MaxBodyLength, Req) ->
%% Multipart API. %% Multipart API.
%% @doc Return the next part's headers.
-spec part(Req) -spec part(Req)
-> {ok, cow_multipart:headers(), Req} | {done, Req} -> {ok, cow_multipart:headers(), Req} | {done, Req}
when Req::req(). when Req::req().
@ -808,7 +692,6 @@ part(Buffer, Req=#http_req{multipart={Boundary, _}}) ->
{done, Req#http_req{multipart=undefined}} {done, Req#http_req{multipart=undefined}}
end. end.
%% @doc Return the current part's body.
-spec part_body(Req) -spec part_body(Req)
-> {ok, binary(), Req} | {more, binary(), Req} -> {ok, binary(), Req} | {more, binary(), Req}
when Req::req(). when Req::req().
@ -855,8 +738,6 @@ stream_multipart(Req=#http_req{multipart={Boundary, Buffer}}) ->
%% Response API. %% Response API.
%% @doc Add a cookie header to the response.
%%
%% The cookie name cannot contain any of the following characters: %% The cookie name cannot contain any of the following characters:
%% =,;\s\t\r\n\013\014 %% =,;\s\t\r\n\013\014
%% %%
@ -868,46 +749,19 @@ set_resp_cookie(Name, Value, Opts, Req) ->
Cookie = cow_cookie:setcookie(Name, Value, Opts), Cookie = cow_cookie:setcookie(Name, Value, Opts),
set_resp_header(<<"set-cookie">>, Cookie, Req). set_resp_header(<<"set-cookie">>, Cookie, Req).
%% @doc Add a header to the response.
-spec set_resp_header(binary(), iodata(), Req) -spec set_resp_header(binary(), iodata(), Req)
-> Req when Req::req(). -> Req when Req::req().
set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) -> set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
Req#http_req{resp_headers=[{Name, Value}|RespHeaders]}. Req#http_req{resp_headers=[{Name, Value}|RespHeaders]}.
%% @doc Add a body to the response.
%%
%% The body set here is ignored if the response is later sent using
%% anything other than reply/2 or reply/3. The response body is expected
%% to be a binary or an iolist.
-spec set_resp_body(iodata(), Req) -> Req when Req::req(). -spec set_resp_body(iodata(), Req) -> Req when Req::req().
set_resp_body(Body, Req) -> set_resp_body(Body, Req) ->
Req#http_req{resp_body=Body}. Req#http_req{resp_body=Body}.
%% @doc Add a body stream function to the response.
%%
%% The body set here is ignored if the response is later sent using
%% anything other than reply/2 or reply/3.
%%
%% Setting a response stream function without a length means that the
%% body will be sent until the connection is closed. Cowboy will make
%% sure that the connection is closed with no extra step required.
%%
%% To inform the client that a body has been sent with this request,
%% Cowboy will add a "Transfer-Encoding: identity" header to the
%% response.
-spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req(). -spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req().
set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) -> set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) ->
Req#http_req{resp_body=StreamFun}. Req#http_req{resp_body=StreamFun}.
%% @doc Add a body function to the response.
%%
%% The body set here is ignored if the response is later sent using
%% anything other than reply/2 or reply/3.
%%
%% Cowboy will call the given response stream function after sending the
%% headers. This function must send the specified number of bytes to the
%% socket it will receive as argument.
%%
%% If the body function crashes while writing the response body or writes %% If the body function crashes while writing the response body or writes
%% fewer bytes than declared the behaviour is undefined. %% fewer bytes than declared the behaviour is undefined.
-spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req) -spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req)
@ -921,12 +775,10 @@ set_resp_body_fun(chunked, StreamFun, Req)
when is_function(StreamFun) -> when is_function(StreamFun) ->
Req#http_req{resp_body={chunked, StreamFun}}. Req#http_req{resp_body={chunked, StreamFun}}.
%% @doc Return whether the given header has been set for the response.
-spec has_resp_header(binary(), req()) -> boolean(). -spec has_resp_header(binary(), req()) -> boolean().
has_resp_header(Name, #http_req{resp_headers=RespHeaders}) -> has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
lists:keymember(Name, 1, RespHeaders). lists:keymember(Name, 1, RespHeaders).
%% @doc Return whether a body has been set for the response.
-spec has_resp_body(req()) -> boolean(). -spec has_resp_body(req()) -> boolean().
has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) -> has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) ->
true; true;
@ -937,25 +789,21 @@ has_resp_body(#http_req{resp_body={Length, _}}) ->
has_resp_body(#http_req{resp_body=RespBody}) -> has_resp_body(#http_req{resp_body=RespBody}) ->
iolist_size(RespBody) > 0. iolist_size(RespBody) > 0.
%% @doc Remove a header previously set for the response.
-spec delete_resp_header(binary(), Req) -spec delete_resp_header(binary(), Req)
-> Req when Req::req(). -> Req when Req::req().
delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) -> delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) ->
RespHeaders2 = lists:keydelete(Name, 1, RespHeaders), RespHeaders2 = lists:keydelete(Name, 1, RespHeaders),
Req#http_req{resp_headers=RespHeaders2}. Req#http_req{resp_headers=RespHeaders2}.
%% @equiv reply(Status, [], [], Req)
-spec reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req(). -spec reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req().
reply(Status, Req=#http_req{resp_body=Body}) -> reply(Status, Req=#http_req{resp_body=Body}) ->
reply(Status, [], Body, Req). reply(Status, [], Body, Req).
%% @equiv reply(Status, Headers, [], Req)
-spec reply(cowboy:http_status(), cowboy:http_headers(), Req) -spec reply(cowboy:http_status(), cowboy:http_headers(), Req)
-> {ok, Req} when Req::req(). -> {ok, Req} when Req::req().
reply(Status, Headers, Req=#http_req{resp_body=Body}) -> reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
reply(Status, Headers, Body, Req). reply(Status, Headers, Body, Req).
%% @doc Send a reply to the client.
-spec reply(cowboy:http_status(), cowboy:http_headers(), -spec reply(cowboy:http_status(), cowboy:http_headers(),
iodata() | {non_neg_integer() | resp_body_fun()}, Req) iodata() | {non_neg_integer() | resp_body_fun()}, Req)
-> {ok, Req} when Req::req(). -> {ok, Req} when Req::req().
@ -1083,22 +931,16 @@ reply_no_compress(Status, Headers, Body, Req,
Req), Req),
Req2. Req2.
%% @equiv chunked_reply(Status, [], Req)
-spec chunked_reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req(). -spec chunked_reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req().
chunked_reply(Status, Req) -> chunked_reply(Status, Req) ->
chunked_reply(Status, [], Req). chunked_reply(Status, [], Req).
%% @doc Initiate the sending of a chunked reply to the client.
%% @see cowboy_req:chunk/2
-spec chunked_reply(cowboy:http_status(), cowboy:http_headers(), Req) -spec chunked_reply(cowboy:http_status(), cowboy:http_headers(), Req)
-> {ok, Req} when Req::req(). -> {ok, Req} when Req::req().
chunked_reply(Status, Headers, Req) -> chunked_reply(Status, Headers, Req) ->
{_, Req2} = chunked_response(Status, Headers, Req), {_, Req2} = chunked_response(Status, Headers, Req),
{ok, Req2}. {ok, Req2}.
%% @doc Send a chunk of data.
%%
%% A chunked reply must have been initiated before calling this function.
-spec chunk(iodata(), req()) -> ok | {error, atom()}. -spec chunk(iodata(), req()) -> ok | {error, atom()}.
chunk(_Data, #http_req{method= <<"HEAD">>}) -> chunk(_Data, #http_req{method= <<"HEAD">>}) ->
ok; ok;
@ -1113,8 +955,7 @@ chunk(Data, #http_req{socket=Socket, transport=Transport,
Transport:send(Socket, [integer_to_list(iolist_size(Data), 16), Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
<<"\r\n">>, Data, <<"\r\n">>]). <<"\r\n">>, Data, <<"\r\n">>]).
%% @doc Finish the chunked reply. %% If ever made public, need to send nothing if HEAD.
%% @todo If ever made public, need to send nothing if HEAD.
-spec last_chunk(Req) -> Req when Req::req(). -spec last_chunk(Req) -> Req when Req::req().
last_chunk(Req=#http_req{socket=Socket, transport=cowboy_spdy}) -> last_chunk(Req=#http_req{socket=Socket, transport=cowboy_spdy}) ->
_ = cowboy_spdy:stream_close(Socket), _ = cowboy_spdy:stream_close(Socket),
@ -1123,8 +964,6 @@ last_chunk(Req=#http_req{socket=Socket, transport=Transport}) ->
_ = Transport:send(Socket, <<"0\r\n\r\n">>), _ = Transport:send(Socket, <<"0\r\n\r\n">>),
Req#http_req{resp_state=done}. Req#http_req{resp_state=done}.
%% @doc Send an upgrade reply.
%% @private
-spec upgrade_reply(cowboy:http_status(), cowboy:http_headers(), Req) -spec upgrade_reply(cowboy:http_status(), cowboy:http_headers(), Req)
-> {ok, Req} when Req::req(). -> {ok, Req} when Req::req().
upgrade_reply(Status, Headers, Req=#http_req{transport=Transport, upgrade_reply(Status, Headers, Req=#http_req{transport=Transport,
@ -1135,10 +974,7 @@ upgrade_reply(Status, Headers, Req=#http_req{transport=Transport,
], <<>>, Req), ], <<>>, Req),
{ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}. {ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
%% @doc Send a reply if one hasn't been sent already.
%%
%% Meant to be used internally for sending errors after crashes. %% Meant to be used internally for sending errors after crashes.
%% @private
-spec maybe_reply(cowboy:http_status(), req()) -> ok. -spec maybe_reply(cowboy:http_status(), req()) -> ok.
maybe_reply(Status, Req) -> maybe_reply(Status, Req) ->
receive receive
@ -1148,8 +984,6 @@ maybe_reply(Status, Req) ->
ok ok
end. end.
%% @doc Ensure the response has been sent fully.
%% @private
-spec ensure_response(req(), cowboy:http_status()) -> ok. -spec ensure_response(req(), cowboy:http_status()) -> ok.
%% The response has already been fully sent to the client. %% The response has already been fully sent to the client.
ensure_response(#http_req{resp_state=done}, _) -> ensure_response(#http_req{resp_state=done}, _) ->
@ -1171,12 +1005,10 @@ ensure_response(#http_req{}, _) ->
%% Private setter/getter API. %% Private setter/getter API.
%% @private
-spec append_buffer(binary(), Req) -> Req when Req::req(). -spec append_buffer(binary(), Req) -> Req when Req::req().
append_buffer(Suffix, Req=#http_req{buffer=Buffer}) -> append_buffer(Suffix, Req=#http_req{buffer=Buffer}) ->
Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}. Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}.
%% @private
-spec get(atom(), req()) -> any(); ([atom()], req()) -> any(). -spec get(atom(), req()) -> any(); ([atom()], req()) -> any().
get(List, Req) when is_list(List) -> get(List, Req) when is_list(List) ->
[g(Atom, Req) || Atom <- List]; [g(Atom, Req) || Atom <- List];
@ -1211,7 +1043,6 @@ g(socket, #http_req{socket=Ret}) -> Ret;
g(transport, #http_req{transport=Ret}) -> Ret; g(transport, #http_req{transport=Ret}) -> Ret;
g(version, #http_req{version=Ret}) -> Ret. g(version, #http_req{version=Ret}) -> Ret.
%% @private
-spec set([{atom(), any()}], Req) -> Req when Req::req(). -spec set([{atom(), any()}], Req) -> Req when Req::req().
set([], Req) -> Req; set([], Req) -> Req;
set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val}); set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val});
@ -1241,7 +1072,6 @@ set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val});
set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val}); set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val});
set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}). set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}).
%% @private
-spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(), -spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(),
cowboy_router:bindings(), Req) -> Req when Req::req(). cowboy_router:bindings(), Req) -> Req when Req::req().
set_bindings(HostInfo, PathInfo, Bindings, Req) -> set_bindings(HostInfo, PathInfo, Bindings, Req) ->
@ -1250,13 +1080,6 @@ set_bindings(HostInfo, PathInfo, Bindings, Req) ->
%% Misc API. %% Misc API.
%% @doc Compact the request data by removing all non-system information.
%%
%% This essentially removes the host and path info, query string, bindings,
%% headers and cookies.
%%
%% Use it when you really need to save up memory, for example when having
%% many concurrent long-running connections.
-spec compact(Req) -> Req when Req::req(). -spec compact(Req) -> Req when Req::req().
compact(Req) -> compact(Req) ->
Req#http_req{host_info=undefined, Req#http_req{host_info=undefined,
@ -1264,13 +1087,10 @@ compact(Req) ->
bindings=undefined, headers=[], bindings=undefined, headers=[],
p_headers=[], cookies=[]}. p_headers=[], cookies=[]}.
%% @doc Prevent any further responses.
%% @private
-spec lock(Req) -> Req when Req::req(). -spec lock(Req) -> Req when Req::req().
lock(Req) -> lock(Req) ->
Req#http_req{resp_state=locked}. Req#http_req{resp_state=locked}.
%% @doc Convert the Req object to a list of key/values.
-spec to_list(req()) -> [{atom(), any()}]. -spec to_list(req()) -> [{atom(), any()}].
to_list(Req) -> to_list(Req) ->
lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))). lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))).
@ -1405,9 +1225,6 @@ atom_to_connection(keepalive) ->
atom_to_connection(close) -> atom_to_connection(close) ->
<<"close">>. <<"close">>.
%% @doc Walk through a tokens list and return whether
%% the connection is keepalive or closed.
%%
%% We don't match on "keep-alive" since it is the default value. %% We don't match on "keep-alive" since it is the default value.
-spec connection_to_atom([binary()]) -> keepalive | close. -spec connection_to_atom([binary()]) -> keepalive | close.
connection_to_atom([]) -> connection_to_atom([]) ->
@ -1480,7 +1297,6 @@ status(B) when is_binary(B) -> B.
%% Tests. %% Tests.
-ifdef(TEST). -ifdef(TEST).
url_test() -> url_test() ->
{undefined, _} = {undefined, _} =
url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined, url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined,
@ -1509,7 +1325,6 @@ url_test() ->
ok. ok.
connection_to_atom_test_() -> connection_to_atom_test_() ->
%% {Tokens, Result}
Tests = [ Tests = [
{[<<"close">>], close}, {[<<"close">>], close},
{[<<"keep-alive">>], keepalive}, {[<<"keep-alive">>], keepalive},
@ -1533,5 +1348,4 @@ merge_headers_test_() ->
{<<"server">>,<<"Cowboy">>}]} {<<"server">>,<<"Cowboy">>}]}
], ],
[fun() -> Res = merge_headers(L,R) end || {L, R, Res} <- Tests]. [fun() -> Res = merge_headers(L,R) end || {L, R, Res} <- Tests].
-endif. -endif.

View file

@ -12,8 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc REST protocol implementation.
%%
%% Originally based on the Webmachine Diagram from Alan Dean and %% Originally based on the Webmachine Diagram from Alan Dean and
%% Justin Sheehy. %% Justin Sheehy.
-module(cowboy_rest). -module(cowboy_rest).
@ -57,11 +55,6 @@
expires :: undefined | no_call | calendar:datetime() expires :: undefined | no_call | calendar:datetime()
}). }).
%% @doc Upgrade a HTTP request to the REST protocol.
%%
%% You do not need to call this function manually. To upgrade to the REST
%% protocol, you simply need to return <em>{upgrade, protocol, {@module}}</em>
%% in your <em>cowboy_http_handler:init/3</em> handler function.
-spec upgrade(Req, Env, module(), any()) -spec upgrade(Req, Env, module(), any())
-> {ok, Req, Env} | {error, 500, Req} -> {ok, Req, Env} | {error, 500, Req}
when Req::cowboy_req:req(), Env::cowboy_middleware:env(). when Req::cowboy_req:req(), Env::cowboy_middleware:env().

View file

@ -12,7 +12,7 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Routing middleware. %% Routing middleware.
%% %%
%% Resolve the handler to be used for the request based on the %% Resolve the handler to be used for the request based on the
%% routing information found in the <em>dispatch</em> environment value. %% routing information found in the <em>dispatch</em> environment value.
@ -51,8 +51,6 @@
-opaque dispatch_rules() :: [dispatch_rule()]. -opaque dispatch_rules() :: [dispatch_rule()].
-export_type([dispatch_rules/0]). -export_type([dispatch_rules/0]).
%% @doc Compile a list of routes into the dispatch format used
%% by Cowboy's routing.
-spec compile(routes()) -> dispatch_rules(). -spec compile(routes()) -> dispatch_rules().
compile(Routes) -> compile(Routes) ->
compile(Routes, []). compile(Routes, []).
@ -162,7 +160,6 @@ compile_brackets_split(<< $], Rest/binary >>, Acc, 0) ->
compile_brackets_split(<< C, Rest/binary >>, Acc, N) -> compile_brackets_split(<< C, Rest/binary >>, Acc, N) ->
compile_brackets_split(Rest, << Acc/binary, C >>, N). compile_brackets_split(Rest, << Acc/binary, C >>, N).
%% @private
-spec execute(Req, Env) -spec execute(Req, Env)
-> {ok, Req, Env} | {error, 400 | 404, Req} -> {ok, Req, Env} | {error, 400 | 404, Req}
when Req::cowboy_req:req(), Env::cowboy_middleware:env(). when Req::cowboy_req:req(), Env::cowboy_middleware:env().
@ -183,7 +180,7 @@ execute(Req, Env) ->
%% Internal. %% Internal.
%% @doc Match hostname tokens and path tokens against dispatch rules. %% Match hostname tokens and path tokens against dispatch rules.
%% %%
%% It is typically used for matching tokens for the hostname and path of %% It is typically used for matching tokens for the hostname and path of
%% the request against a global dispatch rule for your listener. %% the request against a global dispatch rule for your listener.
@ -300,7 +297,6 @@ check_constraint({_, int}, Value) ->
check_constraint({_, function, Fun}, Value) -> check_constraint({_, function, Fun}, Value) ->
Fun(Value). Fun(Value).
%% @doc Split a hostname into a list of tokens.
-spec split_host(binary()) -> tokens(). -spec split_host(binary()) -> tokens().
split_host(Host) -> split_host(Host) ->
split_host(Host, []). split_host(Host, []).
@ -317,8 +313,6 @@ split_host(Host, Acc) ->
split_host(Rest, [Segment|Acc]) split_host(Rest, [Segment|Acc])
end. end.
%% @doc Split a path into a list of path segments.
%%
%% Following RFC2396, this function may return path segments containing any %% Following RFC2396, this function may return path segments containing any
%% character, including <em>/</em> if, and only if, a <em>/</em> was escaped %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
%% and part of a path segment. %% and part of a path segment.
@ -376,9 +370,7 @@ list_match(_List, _Match, _Binds) ->
%% Tests. %% Tests.
-ifdef(TEST). -ifdef(TEST).
compile_test_() -> compile_test_() ->
%% {Routes, Result}
Tests = [ Tests = [
%% Match any host and path. %% Match any host and path.
{[{'_', [{'_', h, o}]}], {[{'_', [{'_', h, o}]}],
@ -433,7 +425,6 @@ compile_test_() ->
fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests]. fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests].
split_host_test_() -> split_host_test_() ->
%% {Host, Result}
Tests = [ Tests = [
{<<"">>, []}, {<<"">>, []},
{<<"*">>, [<<"*">>]}, {<<"*">>, [<<"*">>]},
@ -450,7 +441,6 @@ split_host_test_() ->
[{H, fun() -> R = split_host(H) end} || {H, R} <- Tests]. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
split_path_test_() -> split_path_test_() ->
%% {Path, Result, QueryString}
Tests = [ Tests = [
{<<"/">>, []}, {<<"/">>, []},
{<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]}, {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]},
@ -481,7 +471,6 @@ match_test_() ->
{'_', [], match_any, []} {'_', [], match_any, []}
]} ]}
], ],
%% {Host, Path, Result}
Tests = [ Tests = [
{<<"any">>, <<"/">>, {ok, match_any, [], []}}, {<<"any">>, <<"/">>, {ok, match_any, [], []}},
{<<"www.any.ninenines.eu">>, <<"/users/42/mails">>, {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>,
@ -580,5 +569,4 @@ match_same_bindings_test() ->
{error, notfound, path} = match(Dispatch3, {error, notfound, path} = match(Dispatch3,
<<"ninenines.eu">>, <<"/path/to">>), <<"ninenines.eu">>, <<"/path/to">>),
ok. ok.
-endif. -endif.

View file

@ -12,10 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc SPDY protocol handler.
%%
%% Note that there is no need to monitor these processes when using Cowboy as
%% an application as it already supervises them under the listener supervisor.
-module(cowboy_spdy). -module(cowboy_spdy).
%% API. %% API.
@ -75,7 +71,6 @@
%% API. %% API.
%% @doc Start a SPDY protocol process.
-spec start_link(any(), inet:socket(), module(), any()) -> {ok, pid()}. -spec start_link(any(), inet:socket(), module(), any()) -> {ok, pid()}.
start_link(Ref, Socket, Transport, Opts) -> start_link(Ref, Socket, Transport, Opts) ->
proc_lib:start_link(?MODULE, init, proc_lib:start_link(?MODULE, init,
@ -83,15 +78,13 @@ start_link(Ref, Socket, Transport, Opts) ->
%% Internal. %% Internal.
%% @doc Faster alternative to proplists:get_value/3. %% Faster alternative to proplists:get_value/3.
%% @private
get_value(Key, Opts, Default) -> get_value(Key, Opts, Default) ->
case lists:keyfind(Key, 1, Opts) of case lists:keyfind(Key, 1, Opts) of
{_, Value} -> Value; {_, Value} -> Value;
_ -> Default _ -> Default
end. end.
%% @private
-spec init(pid(), ranch:ref(), inet:socket(), module(), opts()) -> ok. -spec init(pid(), ranch:ref(), inet:socket(), module(), opts()) -> ok.
init(Parent, Ref, Socket, Transport, Opts) -> init(Parent, Ref, Socket, Transport, Opts) ->
process_flag(trap_exit, true), process_flag(trap_exit, true),
@ -394,7 +387,6 @@ execute(Req, Env, [Middleware|Tail]) ->
cowboy_req:maybe_reply(Status, Req2) cowboy_req:maybe_reply(Status, Req2)
end. end.
%% @private
-spec resume(cowboy_middleware:env(), [module()], -spec resume(cowboy_middleware:env(), [module()],
module(), module(), [any()]) -> ok. module(), module(), [any()]) -> ok.
resume(Env, Tail, Module, Function, Args) -> resume(Env, Tail, Module, Function, Args) ->

View file

@ -42,7 +42,7 @@
init(_, _, _) -> init(_, _, _) ->
{upgrade, protocol, cowboy_rest}. {upgrade, protocol, cowboy_rest}.
%% @doc Resolve the file that will be sent and get its file information. %% Resolve the file that will be sent and get its file information.
%% If the handler is configured to manage a directory, check that the %% If the handler is configured to manage a directory, check that the
%% requested file is inside the configured directory. %% requested file is inside the configured directory.
@ -197,7 +197,7 @@ bad_path_win32_check_test_() ->
end} || P <- Tests]. end} || P <- Tests].
-endif. -endif.
%% @doc Reject requests that tried to access a file outside %% Reject requests that tried to access a file outside
%% the target directory. %% the target directory.
-spec malformed_request(Req, State) -spec malformed_request(Req, State)
@ -205,7 +205,7 @@ bad_path_win32_check_test_() ->
malformed_request(Req, State) -> malformed_request(Req, State) ->
{State =:= error, Req, State}. {State =:= error, Req, State}.
%% @doc Directories, files that can't be accessed at all and %% Directories, files that can't be accessed at all and
%% files with no read flag are forbidden. %% files with no read flag are forbidden.
-spec forbidden(Req, State) -spec forbidden(Req, State)
@ -221,7 +221,7 @@ forbidden(Req, State={_, {ok, #file_info{access=Access}}, _})
forbidden(Req, State) -> forbidden(Req, State) ->
{false, Req, State}. {false, Req, State}.
%% @doc Detect the mimetype of the file. %% Detect the mimetype of the file.
-spec content_types_provided(Req, State) -spec content_types_provided(Req, State)
-> {[{binary(), get_file}], Req, State} -> {[{binary(), get_file}], Req, State}
@ -236,7 +236,7 @@ content_types_provided(Req, State={Path, _, Extra}) ->
{[{Type, get_file}], Req, State} {[{Type, get_file}], Req, State}
end. end.
%% @doc Assume the resource doesn't exist if it's not a regular file. %% Assume the resource doesn't exist if it's not a regular file.
-spec resource_exists(Req, State) -spec resource_exists(Req, State)
-> {boolean(), Req, State} -> {boolean(), Req, State}
@ -246,7 +246,7 @@ resource_exists(Req, State={_, {ok, #file_info{type=regular}}, _}) ->
resource_exists(Req, State) -> resource_exists(Req, State) ->
{false, Req, State}. {false, Req, State}.
%% @doc Generate an etag for the file. %% Generate an etag for the file.
-spec generate_etag(Req, State) -spec generate_etag(Req, State)
-> {{strong | weak, binary()}, Req, State} -> {{strong | weak, binary()}, Req, State}
@ -266,7 +266,7 @@ generate_default_etag(Size, Mtime) ->
{strong, list_to_binary(integer_to_list( {strong, list_to_binary(integer_to_list(
erlang:phash2({Size, Mtime}, 16#ffffffff)))}. erlang:phash2({Size, Mtime}, 16#ffffffff)))}.
%% @doc Return the time of last modification of the file. %% Return the time of last modification of the file.
-spec last_modified(Req, State) -spec last_modified(Req, State)
-> {calendar:datetime(), Req, State} -> {calendar:datetime(), Req, State}
@ -274,7 +274,7 @@ generate_default_etag(Size, Mtime) ->
last_modified(Req, State={_, {ok, #file_info{mtime=Modified}}, _}) -> last_modified(Req, State={_, {ok, #file_info{mtime=Modified}}, _}) ->
{Modified, Req, State}. {Modified, Req, State}.
%% @doc Stream the file. %% Stream the file.
%% @todo Export cowboy_req:resp_body_fun()? %% @todo Export cowboy_req:resp_body_fun()?
-spec get_file(Req, State) -spec get_file(Req, State)

View file

@ -13,21 +13,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Behaviour for sub protocols.
%%
%% Only one function needs to be implemented, <em>upgrade/4</em>.
%% It receives the Req, the environment, the handler that the request has been
%% routed to and the handler's options. It acts exactly the same as a
%% middleware, so returns the same values a middleware's execute/2.
%%
%% Once the sub protocol has processed the request it should add the result
%% to the environment. This is done by adding the tuple {result, Value} to the
%% environment list. To continue handling requests on the current connection the
%% Value should be the atom ok. Any other value will prevent the processing of
%% subsequent requests.
%%
%% <em>upgrade/4</em> will be called when a handler's init/3 returns
%% {upgrade, protocol, Module}, where Module is the module of the sub protocol.
-module(cowboy_sub_protocol). -module(cowboy_sub_protocol).
-callback upgrade(Req, Env, module(), any()) -callback upgrade(Req, Env, module(), any())

View file

@ -12,25 +12,15 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @private
-module(cowboy_sup). -module(cowboy_sup).
-behaviour(supervisor). -behaviour(supervisor).
%% API.
-export([start_link/0]). -export([start_link/0]).
%% supervisor.
-export([init/1]). -export([init/1]).
-define(SUPERVISOR, ?MODULE).
%% API.
-spec start_link() -> {ok, pid()}. -spec start_link() -> {ok, pid()}.
start_link() -> start_link() ->
supervisor:start_link({local, ?SUPERVISOR}, ?MODULE, []). supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% supervisor.
init([]) -> init([]) ->
Procs = [{cowboy_clock, {cowboy_clock, start_link, []}, Procs = [{cowboy_clock, {cowboy_clock, start_link, []},

View file

@ -12,8 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Websocket protocol implementation.
%%
%% Cowboy supports versions 7 through 17 of the Websocket drafts. %% Cowboy supports versions 7 through 17 of the Websocket drafts.
%% It also supports RFC6455, the proposed standard for Websocket. %% It also supports RFC6455, the proposed standard for Websocket.
-module(cowboy_websocket). -module(cowboy_websocket).
@ -23,10 +21,7 @@
%% @todo Remove when we support only R16B+. %% @todo Remove when we support only R16B+.
-compile(nowarn_deprecated_function). -compile(nowarn_deprecated_function).
%% API.
-export([upgrade/4]). -export([upgrade/4]).
%% Internal.
-export([handler_loop/4]). -export([handler_loop/4]).
-type close_code() :: 1000..4999. -type close_code() :: 1000..4999.
@ -62,11 +57,6 @@
deflate_state :: undefined | port() deflate_state :: undefined | port()
}). }).
%% @doc Upgrade an HTTP request to the Websocket protocol.
%%
%% You do not need to call this function manually. To upgrade to the Websocket
%% protocol, you simply need to return <em>{upgrade, protocol, {@module}}</em>
%% in your <em>cowboy_http_handler:init/3</em> handler function.
-spec upgrade(Req, Env, module(), any()) -spec upgrade(Req, Env, module(), any())
-> {ok, Req, Env} | {error, 400, Req} -> {ok, Req, Env} | {error, 400, Req}
| {suspend, module(), atom(), [any()]} | {suspend, module(), atom(), [any()]}
@ -215,7 +205,6 @@ handler_loop_timeout(State=#state{timeout=Timeout, timeout_ref=PrevRef}) ->
TRef = erlang:start_timer(Timeout, self(), ?MODULE), TRef = erlang:start_timer(Timeout, self(), ?MODULE),
State#state{timeout_ref=TRef}. State#state{timeout_ref=TRef}.
%% @private
-spec handler_loop(#state{}, Req, any(), binary()) -spec handler_loop(#state{}, Req, any(), binary())
-> {ok, Req, cowboy_middleware:env()} -> {ok, Req, cowboy_middleware:env()}
| {suspend, module(), atom(), [any()]} | {suspend, module(), atom(), [any()]}

View file

@ -12,40 +12,6 @@
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc Handler for HTTP WebSocket requests.
%%
%% WebSocket handlers must implement five callbacks: <em>init/3</em>,
%% <em>websocket_init/3</em>, <em>websocket_handle/3</em>,
%% <em>websocket_info/3</em> and <em>websocket_terminate/3</em>.
%% These callbacks will only be called if the connection is upgraded
%% to WebSocket in the HTTP handler's <em>init/3</em> callback.
%% They are then called in that order, although <em>websocket_handle/3</em>
%% will be called for each packet received, and <em>websocket_info</em>
%% for each message received.
%%
%% <em>websocket_init/3</em> is meant for initialization. It receives
%% information about the transport and protocol used, along with the handler
%% options from the dispatch list. You can define a request-wide state here.
%% If you are going to want to compact the request, you should probably do it
%% here.
%%
%% <em>websocket_handle/3</em> receives the data from the socket. It can reply
%% something, do nothing or close the connection.
%%
%% <em>websocket_info/3</em> receives messages sent to the process. It has
%% the same reply format as <em>websocket_handle/3</em> described above. Note
%% that unlike in a <em>gen_server</em>, when <em>websocket_info/3</em>
%% replies something, it is always to the socket, not to the process that
%% originated the message.
%%
%% <em>websocket_terminate/3</em> is meant for cleaning up. It also receives
%% the request and the state previously defined, along with a reason for
%% termination.
%%
%% All of <em>websocket_init/3</em>, <em>websocket_handle/3</em> and
%% <em>websocket_info/3</em> can decide to hibernate the process by adding
%% an extra element to the returned tuple, containing the atom
%% <em>hibernate</em>. Doing so helps save memory and improve CPU usage.
-module(cowboy_websocket_handler). -module(cowboy_websocket_handler).
-type opts() :: any(). -type opts() :: any().