From 17af50812c47f5dec7e02e443c551b9697715729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Wed, 26 Mar 2014 19:05:59 +0100 Subject: Remove outdated comments, all edoc, plus a few minor tweaks --- src/cowboy.erl | 14 +-- src/cowboy_app.erl | 4 - src/cowboy_bstr.erl | 14 +-- src/cowboy_clock.erl | 29 ++---- src/cowboy_handler.erl | 8 +- src/cowboy_http.erl | 53 +---------- src/cowboy_http_handler.erl | 17 ---- src/cowboy_loop_handler.erl | 23 ----- src/cowboy_middleware.erl | 11 --- src/cowboy_protocol.erl | 40 +-------- src/cowboy_req.erl | 190 +-------------------------------------- src/cowboy_rest.erl | 7 -- src/cowboy_router.erl | 16 +--- src/cowboy_spdy.erl | 10 +-- src/cowboy_static.erl | 16 ++-- src/cowboy_sub_protocol.erl | 15 ---- src/cowboy_sup.erl | 12 +-- src/cowboy_websocket.erl | 11 --- src/cowboy_websocket_handler.erl | 34 ------- 19 files changed, 27 insertions(+), 497 deletions(-) (limited to 'src') diff --git a/src/cowboy.erl b/src/cowboy.erl index 3e838d1..2b50dfb 100644 --- a/src/cowboy.erl +++ b/src/cowboy.erl @@ -12,7 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Convenience API to start and stop HTTP/HTTPS listeners. -module(cowboy). -export([start_http/4]). @@ -37,7 +36,6 @@ fun((http_status(), http_headers(), iodata(), Req) -> Req). -export_type([onresponse_fun/0]). -%% @doc Start an HTTP listener. -spec start_http(ranch:ref(), non_neg_integer(), ranch_tcp:opts(), cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}. start_http(Ref, NbAcceptors, TransOpts, ProtoOpts) @@ -45,7 +43,6 @@ start_http(Ref, NbAcceptors, TransOpts, ProtoOpts) ranch:start_listener(Ref, NbAcceptors, ranch_tcp, TransOpts, cowboy_protocol, ProtoOpts). -%% @doc Start an HTTPS listener. -spec start_https(ranch:ref(), non_neg_integer(), ranch_ssl:opts(), cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}. start_https(Ref, NbAcceptors, TransOpts, ProtoOpts) @@ -53,7 +50,6 @@ start_https(Ref, NbAcceptors, TransOpts, ProtoOpts) ranch:start_listener(Ref, NbAcceptors, ranch_ssl, TransOpts, cowboy_protocol, ProtoOpts). -%% @doc Start a SPDY listener. -spec start_spdy(ranch:ref(), non_neg_integer(), ranch_ssl:opts(), cowboy_spdy:opts()) -> {ok, pid()} | {error, any()}. start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts) @@ -66,20 +62,14 @@ start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts) ranch:start_listener(Ref, NbAcceptors, ranch_ssl, TransOpts2, cowboy_spdy, ProtoOpts). -%% @doc Stop a listener. -spec stop_listener(ranch:ref()) -> ok | {error, not_found}. 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. set_env(Ref, Name, Value) -> Opts = ranch:get_protocol_options(Ref), {_, Env} = lists:keyfind(env, 1, Opts), - Env2 = [{Name, Value}|lists:keydelete(Name, 1, Env)], - Opts2 = lists:keyreplace(env, 1, Opts, {env, Env2}), + Opts2 = lists:keyreplace(env, 1, Opts, + {env, lists:keystore(Name, 1, Env, {Name, Value})}), ok = ranch:set_protocol_options(Ref, Opts2). diff --git a/src/cowboy_app.erl b/src/cowboy_app.erl index d4d0389..f20caf2 100644 --- a/src/cowboy_app.erl +++ b/src/cowboy_app.erl @@ -12,16 +12,12 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @private -module(cowboy_app). -behaviour(application). -%% API. -export([start/2]). -export([stop/1]). -%% API. - start(_Type, _Args) -> cowboy_sup:start_link(). diff --git a/src/cowboy_bstr.erl b/src/cowboy_bstr.erl index 92e3f29..98d2cf7 100644 --- a/src/cowboy_bstr.erl +++ b/src/cowboy_bstr.erl @@ -12,7 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Binary string manipulation. -module(cowboy_bstr). %% Binary strings. @@ -24,11 +23,9 @@ -export([char_to_lower/1]). -export([char_to_upper/1]). -%% @doc Capitalize a token. -%% %% 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 -%% 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 %% badly implemented clients. -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(Rest, false, << Acc/binary, (char_to_lower(C)) >>). -%% @doc Convert a binary string to lowercase. -spec to_lower(B) -> B when B::binary(). to_lower(B) -> << << (char_to_lower(C)) >> || << C >> <= B >>. -%% @doc Convert a binary string to uppercase. -spec to_upper(B) -> B when B::binary(). to_upper(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(). char_to_lower($A) -> $a; char_to_lower($B) -> $b; @@ -85,7 +77,6 @@ char_to_lower($Y) -> $y; char_to_lower($Z) -> $z; char_to_lower(Ch) -> Ch. -%% @doc Convert [a-z] characters to uppercase. -spec char_to_upper(char()) -> char(). char_to_upper($a) -> $A; char_to_upper($b) -> $B; @@ -118,9 +109,7 @@ char_to_upper(Ch) -> Ch. %% Tests. -ifdef(TEST). - capitalize_token_test_() -> - %% {Header, Result} Tests = [ {<<"heLLo-woRld">>, <<"Hello-World">>}, {<<"Sec-Websocket-Version">>, <<"Sec-Websocket-Version">>}, @@ -131,5 +120,4 @@ capitalize_token_test_() -> {<<"Sec-WebSocket---Version">>, <<"Sec-Websocket---Version">>} ], [{H, fun() -> R = capitalize_token(H) end} || {H, R} <- Tests]. - -endif. diff --git a/src/cowboy_clock.erl b/src/cowboy_clock.erl index 8362c99..a8de9bb 100644 --- a/src/cowboy_clock.erl +++ b/src/cowboy_clock.erl @@ -12,8 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% 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 %% the cache of formatted dates every second, all API calls are %% local and directly read from the ETS cache table, providing @@ -41,68 +39,55 @@ tref = undefined :: undefined | timer:tref() }). --define(SERVER, ?MODULE). --define(TABLE, ?MODULE). - %% API. -%% @private -spec start_link() -> {ok, pid()}. start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -%% @private -spec stop() -> stopped. 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(). 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(). rfc1123(DateTime) -> update_rfc1123(<<>>, undefined, DateTime). %% gen_server. -%% @private init([]) -> - ?TABLE = ets:new(?TABLE, [set, protected, + ?MODULE = ets:new(?MODULE, [set, protected, named_table, {read_concurrency, true}]), T = erlang:universaltime(), B = update_rfc1123(<<>>, undefined, T), {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}}. -%% @private handle_call(stop, _From, State=#state{tref=TRef}) -> {ok, cancel} = timer:cancel(TRef), {stop, normal, stopped, State}; handle_call(_Request, _From, State) -> {reply, ignored, State}. -%% @private handle_cast(_Msg, State) -> {noreply, State}. -%% @private handle_info(update, #state{universaltime=Prev, rfc1123=B1, tref=TRef}) -> T = erlang:universaltime(), B2 = update_rfc1123(B1, Prev, T), - ets:insert(?TABLE, {rfc1123, B2}), + ets:insert(?MODULE, {rfc1123, B2}), {noreply, #state{universaltime=T, rfc1123=B2, tref=TRef}}; handle_info(_Info, State) -> {noreply, State}. -%% @private terminate(_Reason, _State) -> ok. -%% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. @@ -174,7 +159,6 @@ month(12) -> <<"Dec">>. %% Tests. -ifdef(TEST). - update_rfc1123_test_() -> Tests = [ {<<"Sat, 14 May 2011 14:25:33 GMT">>, undefined, @@ -215,5 +199,4 @@ pad_int_test_() -> {56, <<"56">>}, {57, <<"57">>}, {58, <<"58">>}, {59, <<"59">>} ], [{I, fun() -> O = pad_int(I) end} || {I, O} <- Tests]. - -endif. diff --git a/src/cowboy_handler.erl b/src/cowboy_handler.erl index ac95de5..7780e20 100644 --- a/src/cowboy_handler.erl +++ b/src/cowboy_handler.erl @@ -12,7 +12,7 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Handler middleware. +%% Handler middleware. %% %% Execute the handler given by the handler and handler_opts %% environment values. The result of this execution is added to the @@ -27,8 +27,6 @@ %% by default. This can be configured through the loop_max_buffer %% environment value. The request will be terminated with an %% {error, overflow} reason if this threshold is reached. -%% -%% @see cowboy_http_handler -module(cowboy_handler). -behaviour(cowboy_middleware). @@ -45,7 +43,6 @@ resp_sent = false :: boolean() }). -%% @private -spec execute(Req, Env) -> {ok, Req, Env} | {error, 500, Req} | {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_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()) -> {ok, Req, cowboy_middleware:env()} | {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), State#state{loop_timeout_ref=TRef}. -%% @private -spec handler_loop(Req, #state{}, module(), any()) -> {ok, Req, cowboy_middleware:env()} | {error, 500, Req} | {suspend, module(), atom(), [any()]} diff --git a/src/cowboy_http.erl b/src/cowboy_http.erl index 8a4fd23..bc8b289 100644 --- a/src/cowboy_http.erl +++ b/src/cowboy_http.erl @@ -13,7 +13,7 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Core HTTP parsing API. +%% Deprecated HTTP parsing API. -module(cowboy_http). %% Parsing. @@ -44,7 +44,6 @@ %% Parsing. -%% @doc Parse a non-empty list of the given type. -spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}. nonempty_list(Data, Fun) -> case list(Data, Fun, []) of @@ -53,7 +52,6 @@ nonempty_list(Data, Fun) -> L -> lists:reverse(L) end. -%% @doc Parse a list of the given type. -spec list(binary(), fun()) -> list() | {error, badarg}. list(Data, Fun) -> case list(Data, Fun, []) of @@ -81,8 +79,6 @@ list(Data, Fun, Acc) -> end) end). -%% @doc Parse a content type. -%% %% We lowercase the charset header as we know it's case insensitive. -spec content_type(binary()) -> any(). content_type(Data) -> @@ -104,7 +100,6 @@ content_type(Data) -> end) end). -%% @doc Parse a media range. -spec media_range(binary(), fun()) -> any(). media_range(Data, Fun) -> media_type(Data, @@ -147,7 +142,6 @@ media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) -> Type, SubType, [{Attr, Value}|Acc]) end). -%% @doc Parse a media type. -spec media_type(binary(), fun()) -> any(). media_type(Data, Fun) -> 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]) end). -%% @doc Parse a conneg header (Accept-Charset, Accept-Encoding), -%% followed by an optional quality value. -spec conneg(binary(), fun()) -> any(). conneg(Data, Fun) -> token_ci(Data, @@ -220,7 +212,6 @@ conneg(Data, Fun) -> end) end). -%% @doc Parse a language range, followed by an optional quality value. -spec language_range(binary(), fun()) -> any(). language_range(<< $*, Rest/binary >>, Fun) -> language_range_ret(Rest, Fun, '*'); @@ -281,12 +272,10 @@ maybe_qparam(Data, Fun) -> Fun(Rest, 1000) end). -%% @doc Parse a quality parameter string (for example q=0.500). -spec qparam(binary(), fun()) -> any(). qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q -> qvalue(Data, Fun). -%% @doc Parse either a list of entity tags or a "*". -spec entity_tag_match(binary()) -> any(). entity_tag_match(<< $*, Rest/binary >>) -> whitespace(Rest, @@ -296,7 +285,6 @@ entity_tag_match(<< $*, Rest/binary >>) -> entity_tag_match(Data) -> nonempty_list(Data, fun entity_tag/2). -%% @doc Parse an entity-tag. -spec entity_tag(binary(), fun()) -> any(). entity_tag(<< "W/", Rest/binary >>, Fun) -> opaque_tag(Rest, Fun, weak); @@ -310,7 +298,6 @@ opaque_tag(Data, Fun, Strength) -> (Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag}) end). -%% @doc Parse an expectation. -spec expectation(binary(), fun()) -> any(). expectation(Data, Fun) -> token_ci(Data, @@ -326,7 +313,6 @@ expectation(Data, Fun) -> Fun(Rest, Expectation) end). -%% @doc Parse a list of parameters (a=b;c=d). -spec params(binary(), fun()) -> any(). params(Data, Fun) -> params(Data, Fun, []). @@ -358,9 +344,6 @@ param(Data, Fun) -> 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, %% it should work fine for our purposes because all HTTP dates should %% be sent as RFC1123 dates in HTTP/1.1. @@ -383,7 +366,6 @@ http_date(Data) -> HTTPDate end. -%% @doc Parse an RFC1123 date. -spec rfc1123_date(binary()) -> any(). rfc1123_date(Data) -> wkday(Data, @@ -403,7 +385,6 @@ rfc1123_date(Data) -> {error, badarg} end). -%% @doc Parse an RFC850 date. -spec rfc850_date(binary()) -> any(). %% From the RFC: %% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date @@ -427,7 +408,6 @@ rfc850_date(Data) -> {error, badarg} end). -%% @doc Parse an asctime date. -spec asctime_date(binary()) -> any(). asctime_date(Data) -> wkday(Data, @@ -586,7 +566,6 @@ time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun) {error, badarg} end. -%% @doc Skip whitespace. -spec whitespace(binary(), fun()) -> any(). whitespace(<< C, Rest/binary >>, Fun) when C =:= $\s; C =:= $\t -> @@ -594,7 +573,6 @@ whitespace(<< C, Rest/binary >>, Fun) whitespace(Data, Fun) -> Fun(Data). -%% @doc Parse a list of digits as a non negative integer. -spec digits(binary()) -> non_neg_integer() | {error, badarg}. digits(Data) -> digits(Data, @@ -621,8 +599,6 @@ digits(<< C, Rest/binary >>, Fun, Acc) digits(Data, Fun, Acc) -> Fun(Data, Acc). -%% @doc Parse a list of case-insensitive alpha characters. -%% %% Changes all characters to lowercase. -spec alpha(binary(), fun()) -> any(). alpha(Data, Fun) -> @@ -639,7 +615,6 @@ alpha(<< C, Rest/binary >>, Fun, Acc) alpha(Data, Fun, Acc) -> Fun(Data, Acc). -%% @doc Parse either a token or a quoted string. -spec word(binary(), fun()) -> any(). word(Data = << $", _/binary >>, Fun) -> quoted_string(Data, Fun); @@ -649,14 +624,11 @@ word(Data, Fun) -> (Rest, Token) -> Fun(Rest, Token) end). -%% @doc Parse a case-insensitive token. -%% %% Changes all characters to lowercase. -spec token_ci(binary(), fun()) -> any(). token_ci(Data, Fun) -> token(Data, Fun, ci, <<>>). -%% @doc Parse a token. -spec token(binary(), fun()) -> any(). token(Data, Fun) -> token(Data, Fun, cs, <<>>). @@ -677,7 +649,6 @@ token(<< C, Rest/binary >>, Fun, Case = ci, Acc) -> token(<< C, Rest/binary >>, Fun, Case, Acc) -> token(Rest, Fun, Case, << Acc/binary, C >>). -%% @doc Parse a quoted string. -spec quoted_string(binary(), fun()) -> any(). quoted_string(<< $", Rest/binary >>, 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(Rest, Fun, << Acc/binary, C >>). -%% @doc Parse a quality value. -spec qvalue(binary(), fun()) -> any(). qvalue(<< $0, $., Rest/binary >>, Fun) -> qvalue(Rest, Fun, 0, 100); @@ -721,8 +691,7 @@ qvalue(<< C, Rest/binary >>, Fun, Q, M) qvalue(Data, Fun, Q, _M) -> Fun(Data, Q). -%% @doc Parse authorization value according rfc 2617. -%% Only Basic authorization is supported so far. +%% Only RFC2617 Basic authorization is supported so far. -spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}. authorization(UserPass, Type = <<"basic">>) -> whitespace(UserPass, @@ -738,7 +707,6 @@ authorization(UserPass, Type = <<"basic">>) -> authorization(String, Type) -> whitespace(String, fun(Rest) -> {Type, Rest} end). -%% @doc Parse user credentials. -spec authorization_basic_userid(binary(), fun()) -> any(). authorization_basic_userid(Data, Fun) -> authorization_basic_userid(Data, Fun, <<>>). @@ -767,7 +735,6 @@ authorization_basic_password(<<>>, Fun, Acc) -> authorization_basic_password(<>, Fun, Acc) -> authorization_basic_password(Rest, Fun, <>). -%% @doc Parse range header according rfc 2616. -spec range(binary()) -> {Unit, [Range]} | {error, badarg} when Unit :: binary(), Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer(). @@ -825,7 +792,6 @@ range_digits(Data, Default, Fun) -> Fun(Data, Default) end). -%% @doc Parse a non empty list of tokens followed with optional parameters. -spec parameterized_tokens(binary()) -> any(). parameterized_tokens(Data) -> nonempty_list(Data, @@ -870,7 +836,6 @@ parameterized_tokens_param(Data, Fun) -> %% Decoding. -%% @doc Decode an identity content. %% @todo Move this to cowlib too I suppose. :-) -spec ce_identity(binary()) -> {ok, binary()}. ce_identity(Data) -> @@ -879,9 +844,7 @@ ce_identity(Data) -> %% Tests. -ifdef(TEST). - nonempty_charset_list_test_() -> - %% {Value, Result} Tests = [ {<<>>, {error, badarg}}, {<<"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]. nonempty_language_range_list_test_() -> - %% {Value, Result} Tests = [ {<<"da, en-gb;q=0.8, en;q=0.7">>, [ {<<"da">>, 1000}, @@ -917,7 +879,6 @@ nonempty_language_range_list_test_() -> || {V, R} <- Tests]. nonempty_token_list_test_() -> - %% {Value, Result} Tests = [ {<<>>, {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]. media_range_list_test_() -> - %% {Tokens, Result} Tests = [ {<<"audio/*; q=0.2, audio/basic">>, [ {{<<"audio">>, <<"*">>, []}, 200, []}, @@ -978,7 +938,6 @@ media_range_list_test_() -> [{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests]. entity_tag_match_test_() -> - %% {Tokens, Result} Tests = [ {<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]}, {<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>, @@ -990,7 +949,6 @@ entity_tag_match_test_() -> [{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests]. http_date_test_() -> - %% {Tokens, Result} Tests = [ {<<"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}}}, @@ -999,28 +957,24 @@ http_date_test_() -> [{V, fun() -> R = http_date(V) end} || {V, R} <- Tests]. rfc1123_date_test_() -> - %% {Tokens, Result} Tests = [ {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}} ], [{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests]. rfc850_date_test_() -> - %% {Tokens, Result} Tests = [ {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}} ], [{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests]. asctime_date_test_() -> - %% {Tokens, Result} Tests = [ {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}} ], [{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests]. content_type_test_() -> - %% {ContentType, Result} Tests = [ {<<"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]. parameterized_tokens_test_() -> - %% {ParameterizedTokens, Result} Tests = [ {<<"foo">>, [{<<"foo">>, []}]}, {<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]}, @@ -1048,7 +1001,6 @@ parameterized_tokens_test_() -> [{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests]. digits_test_() -> - %% {Digits, Result} Tests = [ {<<"42 ">>, 42}, {<<"69\t">>, 69}, @@ -1093,5 +1045,4 @@ http_range_test_() -> {error, badarg}} ], [fun() -> R = range(V) end ||{V, R} <- Tests]. - -endif. diff --git a/src/cowboy_http_handler.erl b/src/cowboy_http_handler.erl index 218e0a4..14c7987 100644 --- a/src/cowboy_http_handler.erl +++ b/src/cowboy_http_handler.erl @@ -12,23 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Behaviour for short-lived HTTP handlers. -%% -%% init/3 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 -%% handle/2 call will simply be skipped. -%% -%% handle/2 allows you to handle the request. It receives the -%% state previously defined. -%% -%% terminate/3 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). -type opts() :: any(). diff --git a/src/cowboy_loop_handler.erl b/src/cowboy_loop_handler.erl index f283f0b..edef77f 100644 --- a/src/cowboy_loop_handler.erl +++ b/src/cowboy_loop_handler.erl @@ -12,29 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Behaviour for long-lived HTTP handlers. -%% -%% init/3 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 info/3 calls will simply be skipped. -%% -%% info/3 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. -%% -%% terminate/3 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). -type opts() :: any(). diff --git a/src/cowboy_middleware.erl b/src/cowboy_middleware.erl index b268366..fa0f5bc 100644 --- a/src/cowboy_middleware.erl +++ b/src/cowboy_middleware.erl @@ -12,17 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Behaviour for middlewares. -%% -%% Only one function needs to be implemented, execute/2. -%% 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). -type env() :: [{atom(), any()}]. diff --git a/src/cowboy_protocol.erl b/src/cowboy_protocol.erl index f0be133..22faf1b 100644 --- a/src/cowboy_protocol.erl +++ b/src/cowboy_protocol.erl @@ -13,39 +13,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc HTTP protocol handler. -%% -%% The available options are: -%%
-%%
compress
Whether to automatically compress the response -%% body when the conditions are met. Disabled by default.
-%%
env
The environment passed and optionally modified -%% by middlewares.
-%%
max_empty_lines
Max number of empty lines before a request. -%% Defaults to 5.
-%%
max_header_name_length
Max length allowed for header names. -%% Defaults to 64.
-%%
max_header_value_length
Max length allowed for header values. -%% Defaults to 4096.
-%%
max_headers
Max number of headers allowed. -%% Defaults to 100.
-%%
max_keepalive
Max number of requests allowed in a single -%% keep-alive session. Defaults to 100.
-%%
max_request_line_length
Max length allowed for the request -%% line. Defaults to 4096.
-%%
middlewares
The list of middlewares to execute when a -%% request is received.
-%%
onrequest
Optional fun that allows Req interaction before -%% any dispatching is done. Host info, path info and bindings are thus -%% not available at this point.
-%%
onresponse
Optional fun that allows replacing a response -%% sent by the application.
-%%
timeout
Time in milliseconds a client has to send the -%% full request line and headers. Defaults to 5000 milliseconds.
-%%
-%% -%% 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). %% API. @@ -93,7 +60,6 @@ %% API. -%% @doc Start an HTTP protocol process. -spec start_link(ranch:ref(), inet:socket(), module(), opts()) -> {ok, pid()}. start_link(Ref, Socket, Transport, Opts) -> Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]), @@ -101,15 +67,13 @@ start_link(Ref, Socket, Transport, Opts) -> %% Internal. -%% @doc Faster alternative to proplists:get_value/3. -%% @private +%% Faster alternative to proplists:get_value/3. get_value(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; _ -> Default end. -%% @private -spec init(ranch:ref(), inet:socket(), module(), opts()) -> ok. init(Ref, Socket, Transport, Opts) -> Compress = get_value(compress, Opts, false), @@ -172,7 +136,6 @@ wait_request(Buffer, State=#state{socket=Socket, transport=Transport, terminate(State) end. -%% @private -spec parse_request(binary(), #state{}, non_neg_integer()) -> ok. %% Empty lines must be using \r\n. parse_request(<< $\n, _/binary >>, State, _) -> @@ -481,7 +444,6 @@ execute(Req, State, Env, [Middleware|Tail]) -> error_terminate(Code, Req2, State) end. -%% @private -spec resume(#state{}, cowboy_middleware:env(), [module()], module(), module(), [any()]) -> ok. resume(State, Env, Tail, Module, Function, Args) -> diff --git a/src/cowboy_req.erl b/src/cowboy_req.erl index 56f55e0..b5f7e2e 100644 --- a/src/cowboy_req.erl +++ b/src/cowboy_req.erl @@ -13,31 +13,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% 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: -%%
-%%
access:
-%%
{Value, Req}
-%%
action:
-%%
{Result, Req} | {Result, Value, Req} | {error, atom()}
-%%
modification:
-%%
Req
-%%
question (has_* or is_*):
-%%
boolean()
-%%
-%% -%% Exceptions include chunk/2 which always returns 'ok', -%% and to_list/1 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 Req 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). %% Request API. @@ -184,13 +159,6 @@ %% 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(), undefined | {inet:ip_address(), inet:port_number()}, binary(), binary(), binary(), @@ -220,65 +188,51 @@ new(Socket, Transport, Peer, Method, Path, Query, end end. -%% @doc Return the HTTP method of the request. -spec method(Req) -> {binary(), Req} when Req::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(). version(Req) -> {Req#http_req.version, Req}. -%% @doc Return the peer address and port number of the remote host. -spec peer(Req) -> {{inet:ip_address(), inet:port_number()}, Req} when Req::req(). peer(Req) -> {Req#http_req.peer, Req}. -%% @doc Return the host binary string. -spec host(Req) -> {binary(), Req} when Req::req(). host(Req) -> {Req#http_req.host, Req}. -%% @doc Return the extra host information obtained from partially matching -%% the hostname using '...'. -spec host_info(Req) -> {cowboy_router:tokens() | undefined, Req} when Req::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(). port(Req) -> {Req#http_req.port, Req}. -%% @doc Return the path binary string. -spec path(Req) -> {binary(), Req} when Req::req(). path(Req) -> {Req#http_req.path, Req}. -%% @doc Return the extra path information obtained from partially matching -%% the patch using '...'. -spec path_info(Req) -> {cowboy_router:tokens() | undefined, Req} when Req::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(). qs(Req) -> {Req#http_req.qs, Req}. -%% @equiv qs_val(Name, Req, undefined) -spec qs_val(binary(), Req) -> {binary() | true | undefined, Req} when Req::req(). qs_val(Name, Req) when is_binary(Name) -> 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) -> {binary() | true | Default, Req} when Req::req(), Default::any(). qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default) @@ -291,7 +245,6 @@ qs_val(Name, Req, Default) -> false -> {Default, Req} end. -%% @doc Return the full list of query string values. -spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req(). qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) -> 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}) -> {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. -%% @see cowboy_req:url/1 -spec host_url(Req) -> {undefined | binary(), Req} when Req::req(). host_url(Req=#http_req{port=undefined}) -> {undefined, Req}; @@ -319,8 +269,6 @@ host_url(Req=#http_req{transport=Transport, host=Host, port=Port}) -> end, {<< "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. -spec url(Req) -> {undefined | binary(), Req} when Req::req(). url(Req=#http_req{}) -> @@ -336,13 +284,10 @@ url(HostURL, Req=#http_req{path=Path, qs=QS}) -> end, {<< HostURL/binary, Path/binary, QS2/binary >>, Req}. -%% @equiv binding(Name, Req, undefined) -spec binding(atom(), Req) -> {any() | undefined, Req} when Req::req(). binding(Name, Req) when is_atom(Name) -> 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) -> {any() | Default, Req} when Req::req(), Default::any(). binding(Name, Req, Default) when is_atom(Name) -> @@ -351,18 +296,15 @@ binding(Name, Req, Default) when is_atom(Name) -> false -> {Default, Req} end. -%% @doc Return the full list of binding values. -spec bindings(Req) -> {[{atom(), any()}], Req} when Req::req(). bindings(Req) -> {Req#http_req.bindings, Req}. -%% @equiv header(Name, Req, undefined) -spec header(binary(), Req) -> {binary() | undefined, Req} when Req::req(). header(Name, Req) -> header(Name, Req, undefined). -%% @doc Return the header value for the given key, or a default if missing. -spec header(binary(), Req, Default) -> {binary() | Default, Req} when Req::req(), Default::any(). header(Name, Req, Default) -> @@ -371,16 +313,10 @@ header(Name, Req, Default) -> false -> {Default, Req} end. -%% @doc Return the full list of headers. -spec headers(Req) -> {cowboy:http_headers(), Req} when Req::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) -> {ok, any(), Req} | {undefined, binary(), Req} | {error, badarg} when Req::req(). @@ -390,14 +326,10 @@ parse_header(Name, Req=#http_req{p_headers=PHeaders}) -> {Name, Value} -> {ok, Value, Req} end. -%% @doc Default values for semantic header parsing. -spec parse_header_default(binary()) -> any(). parse_header_default(<<"transfer-encoding">>) -> [<<"identity">>]; 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()) -> {ok, any(), Req} | {undefined, binary(), Req} | {error, badarg} when Req::req(). @@ -481,14 +413,11 @@ parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) -> end end. -%% @equiv cookie(Name, Req, undefined) -spec cookie(binary(), Req) -> {binary() | undefined, Req} when Req::req(). cookie(Name, Req) when is_binary(Name) -> cookie(Name, Req, undefined). -%% @doc Return the cookie value for the given key, or a default if -%% missing. -spec cookie(binary(), Req, Default) -> {binary() | Default, Req} when Req::req(), Default::any(). cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) -> @@ -504,7 +433,6 @@ cookie(Name, Req, Default) -> false -> {Default, Req} end. -%% @doc Return the full list of cookie values. -spec cookies(Req) -> {list({binary(), binary()}), Req} when Req::req(). cookies(Req=#http_req{cookies=undefined}) -> case parse_header(<<"cookie">>, Req) of @@ -519,16 +447,10 @@ cookies(Req=#http_req{cookies=undefined}) -> cookies(Req=#http_req{cookies=Cookies}) -> {Cookies, Req}. -%% @equiv meta(Name, Req, undefined) -spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req(). meta(Name, Req) -> 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(). meta(Name, Req, Default) -> case lists:keyfind(Name, 1, Req#http_req.meta) of @@ -536,18 +458,12 @@ meta(Name, Req, Default) -> false -> {Default, Req} 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(). 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. -%% @doc Return whether the request message has a body. -spec has_body(req()) -> boolean(). has_body(Req) -> 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) end. -%% @doc Return the request message body length, if known. -%% %% 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. -spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req(). @@ -573,12 +487,6 @@ body_length(Req) -> {undefined, Req2} 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 %% transferred data, and then another is applied to the actual content. %% @@ -587,34 +495,17 @@ body_length(Req) -> %% also initialized through this function. %% %% 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) -> {ok, Req} when Req::req(). init_stream(TransferDecode, TransferState, ContentDecode, Req) -> {ok, Req#http_req{body_state= {stream, 0, TransferDecode, TransferState, ContentDecode}}}. -%% @equiv stream_body(1000000, Req) -spec stream_body(Req) -> {ok, binary(), Req} | {done, Req} | {error, atom()} when Req::req(). stream_body(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} | {done, Req} | {error, atom()} when Req::req(). 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, headers=Headers3, p_headers=PHeaders3}. -%% @todo Probably needs a Rest. -spec content_decode(content_decode_fun(), binary(), Req) -> {ok, binary(), Req} | {error, atom()} when Req::req(). content_decode(ContentDecode, Data, Req) -> @@ -719,12 +609,10 @@ content_decode(ContentDecode, Data, Req) -> {error, Reason} -> {error, Reason} end. -%% @equiv body(8000000, Req) -spec body(Req) -> {ok, binary(), Req} | {error, atom()} when Req::req(). body(Req) -> body(8000000, Req). -%% @doc Return the body sent with the request. -spec body(non_neg_integer() | infinity, Req) -> {ok, binary(), Req} | {error, atom()} when Req::req(). body(MaxBodyLength, Req) -> @@ -760,15 +648,12 @@ skip_body(Req) -> {error, Reason} -> {error, Reason} end. -%% @equiv body_qs(16000, Req) -spec body_qs(Req) -> {ok, [{binary(), binary() | true}], Req} | {error, atom()} when Req::req(). body_qs(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. -spec body_qs(non_neg_integer() | infinity, Req) -> {ok, [{binary(), binary() | true}], Req} | {error, atom()} @@ -783,7 +668,6 @@ body_qs(MaxBodyLength, Req) -> %% Multipart API. -%% @doc Return the next part's headers. -spec part(Req) -> {ok, cow_multipart:headers(), Req} | {done, Req} when Req::req(). @@ -808,7 +692,6 @@ part(Buffer, Req=#http_req{multipart={Boundary, _}}) -> {done, Req#http_req{multipart=undefined}} end. -%% @doc Return the current part's body. -spec part_body(Req) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req(). @@ -855,8 +738,6 @@ stream_multipart(Req=#http_req{multipart={Boundary, Buffer}}) -> %% Response API. -%% @doc Add a cookie header to the response. -%% %% The cookie name cannot contain any of the following characters: %% =,;\s\t\r\n\013\014 %% @@ -868,46 +749,19 @@ set_resp_cookie(Name, Value, Opts, Req) -> Cookie = cow_cookie:setcookie(Name, Value, Opts), set_resp_header(<<"set-cookie">>, Cookie, Req). -%% @doc Add a header to the response. -spec set_resp_header(binary(), iodata(), Req) -> Req when Req::req(). set_resp_header(Name, Value, Req=#http_req{resp_headers=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(). set_resp_body(Body, Req) -> 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(). set_resp_body_fun(StreamFun, Req) when is_function(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 %% fewer bytes than declared the behaviour is undefined. -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) -> 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(). has_resp_header(Name, #http_req{resp_headers=RespHeaders}) -> lists:keymember(Name, 1, RespHeaders). -%% @doc Return whether a body has been set for the response. -spec has_resp_body(req()) -> boolean(). has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) -> true; @@ -937,25 +789,21 @@ has_resp_body(#http_req{resp_body={Length, _}}) -> has_resp_body(#http_req{resp_body=RespBody}) -> iolist_size(RespBody) > 0. -%% @doc Remove a header previously set for the response. -spec delete_resp_header(binary(), Req) -> Req when Req::req(). delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) -> RespHeaders2 = lists:keydelete(Name, 1, RespHeaders), Req#http_req{resp_headers=RespHeaders2}. -%% @equiv reply(Status, [], [], Req) -spec reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req(). reply(Status, Req=#http_req{resp_body=Body}) -> reply(Status, [], Body, Req). -%% @equiv reply(Status, Headers, [], Req) -spec reply(cowboy:http_status(), cowboy:http_headers(), Req) -> {ok, Req} when Req::req(). reply(Status, Headers, Req=#http_req{resp_body=Body}) -> reply(Status, Headers, Body, Req). -%% @doc Send a reply to the client. -spec reply(cowboy:http_status(), cowboy:http_headers(), iodata() | {non_neg_integer() | resp_body_fun()}, Req) -> {ok, Req} when Req::req(). @@ -1083,22 +931,16 @@ reply_no_compress(Status, Headers, Body, Req, Req), Req2. -%% @equiv chunked_reply(Status, [], Req) -spec chunked_reply(cowboy:http_status(), Req) -> {ok, Req} when Req::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) -> {ok, Req} when Req::req(). chunked_reply(Status, Headers, Req) -> {_, Req2} = chunked_response(Status, Headers, Req), {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()}. chunk(_Data, #http_req{method= <<"HEAD">>}) -> ok; @@ -1113,8 +955,7 @@ chunk(Data, #http_req{socket=Socket, transport=Transport, Transport:send(Socket, [integer_to_list(iolist_size(Data), 16), <<"\r\n">>, Data, <<"\r\n">>]). -%% @doc Finish the chunked reply. -%% @todo If ever made public, need to send nothing if HEAD. +%% If ever made public, need to send nothing if HEAD. -spec last_chunk(Req) -> Req when Req::req(). last_chunk(Req=#http_req{socket=Socket, transport=cowboy_spdy}) -> _ = 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">>), Req#http_req{resp_state=done}. -%% @doc Send an upgrade reply. -%% @private -spec upgrade_reply(cowboy:http_status(), cowboy:http_headers(), Req) -> {ok, Req} when Req::req(). upgrade_reply(Status, Headers, Req=#http_req{transport=Transport, @@ -1135,10 +974,7 @@ upgrade_reply(Status, Headers, Req=#http_req{transport=Transport, ], <<>>, Req), {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. -%% @private -spec maybe_reply(cowboy:http_status(), req()) -> ok. maybe_reply(Status, Req) -> receive @@ -1148,8 +984,6 @@ maybe_reply(Status, Req) -> ok end. -%% @doc Ensure the response has been sent fully. -%% @private -spec ensure_response(req(), cowboy:http_status()) -> ok. %% The response has already been fully sent to the client. ensure_response(#http_req{resp_state=done}, _) -> @@ -1171,12 +1005,10 @@ ensure_response(#http_req{}, _) -> %% Private setter/getter API. -%% @private -spec append_buffer(binary(), Req) -> Req when Req::req(). append_buffer(Suffix, Req=#http_req{buffer=Buffer}) -> Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}. -%% @private -spec get(atom(), req()) -> any(); ([atom()], req()) -> any(). get(List, Req) when is_list(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(version, #http_req{version=Ret}) -> Ret. -%% @private -spec set([{atom(), any()}], Req) -> Req when Req::req(). set([], Req) -> Req; 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([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}). -%% @private -spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(), cowboy_router:bindings(), Req) -> Req when Req::req(). set_bindings(HostInfo, PathInfo, Bindings, Req) -> @@ -1250,13 +1080,6 @@ set_bindings(HostInfo, PathInfo, Bindings, Req) -> %% 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(). compact(Req) -> Req#http_req{host_info=undefined, @@ -1264,13 +1087,10 @@ compact(Req) -> bindings=undefined, headers=[], p_headers=[], cookies=[]}. -%% @doc Prevent any further responses. -%% @private -spec lock(Req) -> Req when Req::req(). lock(Req) -> Req#http_req{resp_state=locked}. -%% @doc Convert the Req object to a list of key/values. -spec to_list(req()) -> [{atom(), any()}]. 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) -> <<"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. -spec connection_to_atom([binary()]) -> keepalive | close. connection_to_atom([]) -> @@ -1480,7 +1297,6 @@ status(B) when is_binary(B) -> B. %% Tests. -ifdef(TEST). - url_test() -> {undefined, _} = url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined, @@ -1509,7 +1325,6 @@ url_test() -> ok. connection_to_atom_test_() -> - %% {Tokens, Result} Tests = [ {[<<"close">>], close}, {[<<"keep-alive">>], keepalive}, @@ -1533,5 +1348,4 @@ merge_headers_test_() -> {<<"server">>,<<"Cowboy">>}]} ], [fun() -> Res = merge_headers(L,R) end || {L, R, Res} <- Tests]. - -endif. diff --git a/src/cowboy_rest.erl b/src/cowboy_rest.erl index 3eac8dd..63e4dd9 100644 --- a/src/cowboy_rest.erl +++ b/src/cowboy_rest.erl @@ -12,8 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% 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 %% Justin Sheehy. -module(cowboy_rest). @@ -57,11 +55,6 @@ 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 {upgrade, protocol, {@module}} -%% in your cowboy_http_handler:init/3 handler function. -spec upgrade(Req, Env, module(), any()) -> {ok, Req, Env} | {error, 500, Req} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). diff --git a/src/cowboy_router.erl b/src/cowboy_router.erl index ad9d360..ef91c6d 100644 --- a/src/cowboy_router.erl +++ b/src/cowboy_router.erl @@ -12,7 +12,7 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% 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 %% routing information found in the dispatch environment value. @@ -51,8 +51,6 @@ -opaque dispatch_rules() :: [dispatch_rule()]. -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(). 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(Rest, << Acc/binary, C >>, N). -%% @private -spec execute(Req, Env) -> {ok, Req, Env} | {error, 400 | 404, Req} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). @@ -183,7 +180,7 @@ execute(Req, Env) -> %% 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 %% the request against a global dispatch rule for your listener. @@ -300,7 +297,6 @@ check_constraint({_, int}, Value) -> check_constraint({_, function, Fun}, Value) -> Fun(Value). -%% @doc Split a hostname into a list of tokens. -spec split_host(binary()) -> tokens(). split_host(Host) -> split_host(Host, []). @@ -317,8 +313,6 @@ split_host(Host, Acc) -> split_host(Rest, [Segment|Acc]) end. -%% @doc Split a path into a list of path segments. -%% %% Following RFC2396, this function may return path segments containing any %% character, including / if, and only if, a / was escaped %% and part of a path segment. @@ -376,9 +370,7 @@ list_match(_List, _Match, _Binds) -> %% Tests. -ifdef(TEST). - compile_test_() -> - %% {Routes, Result} Tests = [ %% Match any host and path. {[{'_', [{'_', h, o}]}], @@ -433,7 +425,6 @@ compile_test_() -> fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests]. split_host_test_() -> - %% {Host, Result} Tests = [ {<<"">>, []}, {<<"*">>, [<<"*">>]}, @@ -450,7 +441,6 @@ split_host_test_() -> [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests]. split_path_test_() -> - %% {Path, Result, QueryString} Tests = [ {<<"/">>, []}, {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]}, @@ -481,7 +471,6 @@ match_test_() -> {'_', [], match_any, []} ]} ], - %% {Host, Path, Result} Tests = [ {<<"any">>, <<"/">>, {ok, match_any, [], []}}, {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>, @@ -580,5 +569,4 @@ match_same_bindings_test() -> {error, notfound, path} = match(Dispatch3, <<"ninenines.eu">>, <<"/path/to">>), ok. - -endif. diff --git a/src/cowboy_spdy.erl b/src/cowboy_spdy.erl index 7deb3b8..64ec950 100644 --- a/src/cowboy_spdy.erl +++ b/src/cowboy_spdy.erl @@ -12,10 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% 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). %% API. @@ -75,7 +71,6 @@ %% API. -%% @doc Start a SPDY protocol process. -spec start_link(any(), inet:socket(), module(), any()) -> {ok, pid()}. start_link(Ref, Socket, Transport, Opts) -> proc_lib:start_link(?MODULE, init, @@ -83,15 +78,13 @@ start_link(Ref, Socket, Transport, Opts) -> %% Internal. -%% @doc Faster alternative to proplists:get_value/3. -%% @private +%% Faster alternative to proplists:get_value/3. get_value(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; _ -> Default end. -%% @private -spec init(pid(), ranch:ref(), inet:socket(), module(), opts()) -> ok. init(Parent, Ref, Socket, Transport, Opts) -> process_flag(trap_exit, true), @@ -394,7 +387,6 @@ execute(Req, Env, [Middleware|Tail]) -> cowboy_req:maybe_reply(Status, Req2) end. -%% @private -spec resume(cowboy_middleware:env(), [module()], module(), module(), [any()]) -> ok. resume(Env, Tail, Module, Function, Args) -> diff --git a/src/cowboy_static.erl b/src/cowboy_static.erl index 4bf84da..e979571 100644 --- a/src/cowboy_static.erl +++ b/src/cowboy_static.erl @@ -42,7 +42,7 @@ init(_, _, _) -> {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 %% requested file is inside the configured directory. @@ -197,7 +197,7 @@ bad_path_win32_check_test_() -> end} || P <- Tests]. -endif. -%% @doc Reject requests that tried to access a file outside +%% Reject requests that tried to access a file outside %% the target directory. -spec malformed_request(Req, State) @@ -205,7 +205,7 @@ bad_path_win32_check_test_() -> malformed_request(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. -spec forbidden(Req, State) @@ -221,7 +221,7 @@ forbidden(Req, State={_, {ok, #file_info{access=Access}}, _}) forbidden(Req, State) -> {false, Req, State}. -%% @doc Detect the mimetype of the file. +%% Detect the mimetype of the file. -spec content_types_provided(Req, State) -> {[{binary(), get_file}], Req, State} @@ -236,7 +236,7 @@ content_types_provided(Req, State={Path, _, Extra}) -> {[{Type, get_file}], Req, State} 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) -> {boolean(), Req, State} @@ -246,7 +246,7 @@ resource_exists(Req, State={_, {ok, #file_info{type=regular}}, _}) -> resource_exists(Req, State) -> {false, Req, State}. -%% @doc Generate an etag for the file. +%% Generate an etag for the file. -spec generate_etag(Req, State) -> {{strong | weak, binary()}, Req, State} @@ -266,7 +266,7 @@ generate_default_etag(Size, Mtime) -> {strong, list_to_binary(integer_to_list( 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) -> {calendar:datetime(), Req, State} @@ -274,7 +274,7 @@ generate_default_etag(Size, Mtime) -> last_modified(Req, State={_, {ok, #file_info{mtime=Modified}}, _}) -> {Modified, Req, State}. -%% @doc Stream the file. +%% Stream the file. %% @todo Export cowboy_req:resp_body_fun()? -spec get_file(Req, State) diff --git a/src/cowboy_sub_protocol.erl b/src/cowboy_sub_protocol.erl index ee4701c..713c3cd 100644 --- a/src/cowboy_sub_protocol.erl +++ b/src/cowboy_sub_protocol.erl @@ -13,21 +13,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Behaviour for sub protocols. -%% -%% Only one function needs to be implemented, upgrade/4. -%% 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. -%% -%% upgrade/4 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). -callback upgrade(Req, Env, module(), any()) diff --git a/src/cowboy_sup.erl b/src/cowboy_sup.erl index 21e1810..d9d7878 100644 --- a/src/cowboy_sup.erl +++ b/src/cowboy_sup.erl @@ -12,25 +12,15 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @private -module(cowboy_sup). -behaviour(supervisor). -%% API. -export([start_link/0]). - -%% supervisor. -export([init/1]). --define(SUPERVISOR, ?MODULE). - -%% API. - -spec start_link() -> {ok, pid()}. start_link() -> - supervisor:start_link({local, ?SUPERVISOR}, ?MODULE, []). - -%% supervisor. + supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> Procs = [{cowboy_clock, {cowboy_clock, start_link, []}, diff --git a/src/cowboy_websocket.erl b/src/cowboy_websocket.erl index 528e146..98e25e6 100644 --- a/src/cowboy_websocket.erl +++ b/src/cowboy_websocket.erl @@ -12,8 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% 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. %% It also supports RFC6455, the proposed standard for Websocket. -module(cowboy_websocket). @@ -23,10 +21,7 @@ %% @todo Remove when we support only R16B+. -compile(nowarn_deprecated_function). -%% API. -export([upgrade/4]). - -%% Internal. -export([handler_loop/4]). -type close_code() :: 1000..4999. @@ -62,11 +57,6 @@ 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 {upgrade, protocol, {@module}} -%% in your cowboy_http_handler:init/3 handler function. -spec upgrade(Req, Env, module(), any()) -> {ok, Req, Env} | {error, 400, Req} | {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), State#state{timeout_ref=TRef}. -%% @private -spec handler_loop(#state{}, Req, any(), binary()) -> {ok, Req, cowboy_middleware:env()} | {suspend, module(), atom(), [any()]} diff --git a/src/cowboy_websocket_handler.erl b/src/cowboy_websocket_handler.erl index d6adfa5..177e5f6 100644 --- a/src/cowboy_websocket_handler.erl +++ b/src/cowboy_websocket_handler.erl @@ -12,40 +12,6 @@ %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -%% @doc Handler for HTTP WebSocket requests. -%% -%% WebSocket handlers must implement five callbacks: init/3, -%% websocket_init/3, websocket_handle/3, -%% websocket_info/3 and websocket_terminate/3. -%% These callbacks will only be called if the connection is upgraded -%% to WebSocket in the HTTP handler's init/3 callback. -%% They are then called in that order, although websocket_handle/3 -%% will be called for each packet received, and websocket_info -%% for each message received. -%% -%% websocket_init/3 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. -%% -%% websocket_handle/3 receives the data from the socket. It can reply -%% something, do nothing or close the connection. -%% -%% websocket_info/3 receives messages sent to the process. It has -%% the same reply format as websocket_handle/3 described above. Note -%% that unlike in a gen_server, when websocket_info/3 -%% replies something, it is always to the socket, not to the process that -%% originated the message. -%% -%% websocket_terminate/3 is meant for cleaning up. It also receives -%% the request and the state previously defined, along with a reason for -%% termination. -%% -%% All of websocket_init/3, websocket_handle/3 and -%% websocket_info/3 can decide to hibernate the process by adding -%% an extra element to the returned tuple, containing the atom -%% hibernate. Doing so helps save memory and improve CPU usage. -module(cowboy_websocket_handler). -type opts() :: any(). -- cgit v1.2.3