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

Move the reply function to cowboy_http_req.

This commit is contained in:
Loïc Hoguin 2011-03-18 22:38:26 +01:00
parent c6ad0273a8
commit 408f167621
4 changed files with 116 additions and 108 deletions

View file

@ -69,7 +69,8 @@ handler could be written like this:
{ok, Req, undefined}. {ok, Req, undefined}.
handle(Req, State) -> handle(Req, State) ->
{reply, 200, [], "Hello World!"}. {ok, Req2} = cowboy_http_req:reply(200, [], "Hello World!", Req),
{ok, Req2, State}.
terminate(Req, State) -> terminate(Req, State) ->
ok. ok.

View file

@ -13,17 +13,19 @@
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-record(http_req, { -record(http_req, {
listener = undefined :: undefined | atom(), %% todo socket = undefined :: undefined | socket(),
method = 'GET' :: http_method(), transport = undefined :: undefined | module(),
version = {1, 1} :: http_version(), connection = keepalive :: keepalive | close,
peer = undefined :: undefined | {Address::ip_address(), Port::port_number()}, method = 'GET' :: http_method(),
host = undefined :: undefined | path_tokens(), %% todo version = {1, 1} :: http_version(),
raw_host = undefined :: undefined | string(), %% todo peer = undefined :: undefined | {Address::ip_address(), Port::port_number()},
path = undefined :: undefined | path_tokens(), %% todo host = undefined :: undefined | path_tokens(), %% todo
raw_path = undefined :: undefined | string(), %% todo raw_host = undefined :: undefined | string(), %% todo
qs_vals = undefined :: undefined | bindings(), %% todo path = undefined :: undefined | path_tokens(), %% todo
raw_qs = undefined :: undefined | string(), raw_path = undefined :: undefined | string(), %% todo
bindings = undefined :: undefined | bindings(), qs_vals = undefined :: undefined | bindings(), %% todo
headers = [] :: http_headers() raw_qs = undefined :: undefined | string(),
%% cookies = undefined :: undefined | http_cookies() %% @todo bindings = undefined :: undefined | bindings(),
headers = [] :: http_headers()
%% cookies = undefined :: undefined | http_cookies() %% @todo
}). }).

View file

@ -66,8 +66,8 @@ request({http_request, Method, {abs_path, AbsPath}, Version},
State=#state{socket=Socket, transport=Transport}) -> State=#state{socket=Socket, transport=Transport}) ->
{Path, Qs} = cowboy_dispatcher:split_path(AbsPath), {Path, Qs} = cowboy_dispatcher:split_path(AbsPath),
{ok, Peer} = Transport:peername(Socket), {ok, Peer} = Transport:peername(Socket),
wait_header(#http_req{method=Method, version=Version, wait_header(#http_req{socket=Socket, transport=Transport, method=Method,
peer=Peer, path=Path, raw_qs=Qs}, State). version=Version, peer=Peer, path=Path, raw_qs=Qs}, State).
-spec wait_header(Req::#http_req{}, State::#state{}) -> ok. -spec wait_header(Req::#http_req{}, State::#state{}) -> ok.
%% @todo We don't want to wait T at each header... %% @todo We don't want to wait T at each header...
@ -96,9 +96,10 @@ header({http_header, _I, 'Host', _R, Value}, Req=#http_req{path=Path},
error_terminate(404, State) error_terminate(404, State)
end; end;
header({http_header, _I, 'Connection', _R, Connection}, Req, State) -> header({http_header, _I, 'Connection', _R, Connection}, Req, State) ->
wait_header(Req#http_req{ ConnAtom = connection_to_atom(Connection),
wait_header(Req#http_req{connection=ConnAtom,
headers=[{'Connection', Connection}|Req#http_req.headers]}, headers=[{'Connection', Connection}|Req#http_req.headers]},
State#state{connection=connection_to_atom(Connection)}); State#state{connection=ConnAtom});
header({http_header, _I, Field, _R, Value}, Req, State) -> header({http_header, _I, Field, _R, Value}, Req, State) ->
wait_header(Req#http_req{headers=[{Field, Value}|Req#http_req.headers]}, wait_header(Req#http_req{headers=[{Field, Value}|Req#http_req.headers]},
State); State);
@ -120,11 +121,8 @@ handler_init(Req, State=#state{handler={Handler, Opts}}) ->
State::#state{}) -> ok. State::#state{}) -> ok.
handler_loop(HandlerState, Req, State=#state{handler={Handler, _Opts}}) -> handler_loop(HandlerState, Req, State=#state{handler={Handler, _Opts}}) ->
case Handler:handle(Req, HandlerState) of case Handler:handle(Req, HandlerState) of
%% @todo {ok, Req2, HandlerState2} -> and use them in handler_terminate {ok, Req2, HandlerState2} ->
%% @todo Move the reply code to the cowboy_http_req module. handler_terminate(HandlerState2, Req2, State)
{reply, RCode, RHeaders, RBody} ->
reply(RCode, RHeaders, RBody, State),
handler_terminate(HandlerState, Req, State)
%% @todo {mode, active} %% @todo {mode, active}
end. end.
@ -135,31 +133,23 @@ handler_terminate(HandlerState, Req, State=#state{handler={Handler, _Opts}}) ->
%% @todo We need to check if the Req has been replied to. %% @todo We need to check if the Req has been replied to.
%% All requests must have a reply, at worst an error. %% All requests must have a reply, at worst an error.
%% If a request started but wasn't completed, complete it. %% If a request started but wasn't completed, complete it.
case Res of case {Res, State#state.connection} of
ok -> next_request(State); {ok, keepalive} -> next_request(State);
closed -> terminate(State) _Closed -> terminate(State)
end. end.
-spec error_terminate(Code::http_status(), State::#state{}) -> ok. -spec error_terminate(Code::http_status(), State::#state{}) -> ok.
error_terminate(Code, State) -> error_terminate(Code, State=#state{socket=Socket, transport=Transport,
reply(Code, [], [], State#state{connection=close}). connection=Connection}) ->
cowboy_http_req:reply(Code, [], [], #http_req{socket=Socket,
transport=Transport, connection=Connection}),
terminate(State).
-spec terminate(State::#state{}) -> ok. -spec terminate(State::#state{}) -> ok.
terminate(#state{socket=Socket, transport=Transport}) -> terminate(#state{socket=Socket, transport=Transport}) ->
Transport:close(Socket), Transport:close(Socket),
ok. ok.
-spec reply(Code::http_status(), Headers::http_headers(), Body::iolist(),
State::#state{}) -> ok.
%% @todo Don't be naive about the headers!
reply(Code, Headers, Body, #state{socket=Socket,
transport=TransportMod, connection=Connection}) ->
StatusLine = ["HTTP/1.1 ", status(Code), "\r\n"],
BaseHeaders = ["Connection: ", atom_to_connection(Connection),
"\r\nContent-Length: ", integer_to_list(iolist_size(Body)), "\r\n"],
TransportMod:send(Socket,
[StatusLine, BaseHeaders, Headers, "\r\n", Body]).
-spec next_request(State::#state{}) -> ok. -spec next_request(State::#state{}) -> ok.
next_request(State=#state{connection=keepalive}) -> next_request(State=#state{connection=keepalive}) ->
wait_request(State); wait_request(State);
@ -174,65 +164,3 @@ connection_to_atom(Connection) ->
"close" -> close; "close" -> close;
_Any -> keepalive _Any -> keepalive
end. end.
-spec atom_to_connection(Atom::keepalive | close) -> string().
atom_to_connection(keepalive) ->
"keep-alive";
atom_to_connection(close) ->
"close".
-spec status(Code::http_status()) -> string().
status(100) -> "100 Continue";
status(101) -> "101 Switching Protocols";
status(102) -> "102 Processing";
status(200) -> "200 OK";
status(201) -> "201 Created";
status(202) -> "202 Accepted";
status(203) -> "203 Non-Authoritative Information";
status(204) -> "204 No Content";
status(205) -> "205 Reset Content";
status(206) -> "206 Partial Content";
status(207) -> "207 Multi-Status";
status(226) -> "226 IM Used";
status(300) -> "300 Multiple Choices";
status(301) -> "301 Moved Permanently";
status(302) -> "302 Found";
status(303) -> "303 See Other";
status(304) -> "304 Not Modified";
status(305) -> "305 Use Proxy";
status(306) -> "306 Switch Proxy";
status(307) -> "307 Temporary Redirect";
status(400) -> "400 Bad Request";
status(401) -> "401 Unauthorized";
status(402) -> "402 Payment Required";
status(403) -> "403 Forbidden";
status(404) -> "404 Not Found";
status(405) -> "405 Method Not Allowed";
status(406) -> "406 Not Acceptable";
status(407) -> "407 Proxy Authentication Required";
status(408) -> "408 Request Timeout";
status(409) -> "409 Conflict";
status(410) -> "410 Gone";
status(411) -> "411 Length Required";
status(412) -> "412 Precondition Failed";
status(413) -> "413 Request Entity Too Large";
status(414) -> "414 Request-URI Too Long";
status(415) -> "415 Unsupported Media Type";
status(416) -> "416 Requested Range Not Satisfiable";
status(417) -> "417 Expectation Failed";
status(418) -> "418 I'm a teapot";
status(422) -> "422 Unprocessable Entity";
status(423) -> "423 Locked";
status(424) -> "424 Failed Dependency";
status(425) -> "425 Unordered Collection";
status(426) -> "426 Upgrade Required";
status(500) -> "500 Internal Server Error";
status(501) -> "501 Not Implemented";
status(502) -> "502 Bad Gateway";
status(503) -> "503 Service Unavailable";
status(504) -> "504 Gateway Timeout";
status(505) -> "505 HTTP Version Not Supported";
status(506) -> "506 Variant Also Negotiates";
status(507) -> "507 Insufficient Storage";
status(510) -> "510 Not Extended";
status(L) when is_list(L) -> L.

View file

@ -13,25 +13,26 @@
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(cowboy_http_req). -module(cowboy_http_req).
-export([ -export([
listener/1, method/1, version/1, peer/1, method/1, version/1, peer/1,
host/1, raw_host/1, host/1, raw_host/1,
path/1, raw_path/1, path/1, raw_path/1,
qs_val/2, qs_val/3, qs_vals/1, raw_qs/1, qs_val/2, qs_val/3, qs_vals/1, raw_qs/1,
binding/2, binding/3, bindings/1, binding/2, binding/3, bindings/1,
header/2, header/3, headers/1 header/2, header/3, headers/1
%% cookie/2, cookie/3, cookies/1 @todo %% cookie/2, cookie/3, cookies/1 @todo
]). %% API. ]). %% Request API.
-export([
reply/4
]). %% Response API.
-include("include/types.hrl"). -include("include/types.hrl").
-include("include/http.hrl"). -include("include/http.hrl").
-include_lib("eunit/include/eunit.hrl"). -include_lib("eunit/include/eunit.hrl").
%% API. %% Request API.
-spec listener(Req::#http_req{}) -> {Listener::atom(), Req::#http_req{}}.
listener(Req) ->
{Req#http_req.listener, Req}.
-spec method(Req::#http_req{}) -> {Method::http_method(), Req::#http_req{}}. -spec method(Req::#http_req{}) -> {Method::http_method(), Req::#http_req{}}.
method(Req) -> method(Req) ->
@ -125,6 +126,20 @@ header(Name, Default, Req) ->
headers(Req) -> headers(Req) ->
{Req#http_req.headers, Req}. {Req#http_req.headers, Req}.
%% Response API.
-spec reply(Code::http_status(), Headers::http_headers(),
Body::iolist(), Req::#http_req{}) -> ok.
%% @todo Don't be naive about the headers!
reply(Code, Headers, Body, Req=#http_req{socket=Socket,
transport=Transport, connection=Connection}) ->
StatusLine = ["HTTP/1.1 ", status(Code), "\r\n"],
BaseHeaders = ["Connection: ", atom_to_connection(Connection),
"\r\nContent-Length: ", integer_to_list(iolist_size(Body)), "\r\n"],
Transport:send(Socket,
[StatusLine, BaseHeaders, Headers, "\r\n", Body]),
{ok, Req}.
%% Internal. %% Internal.
-spec parse_qs(Qs::string()) -> list({Name::string(), Value::string()}). -spec parse_qs(Qs::string()) -> list({Name::string(), Value::string()}).
@ -138,6 +153,68 @@ parse_qs(Qs) ->
{Name, Value} {Name, Value}
end || Token <- Tokens]. end || Token <- Tokens].
-spec atom_to_connection(Atom::keepalive | close) -> string().
atom_to_connection(keepalive) ->
"keep-alive";
atom_to_connection(close) ->
"close".
-spec status(Code::http_status()) -> string().
status(100) -> "100 Continue";
status(101) -> "101 Switching Protocols";
status(102) -> "102 Processing";
status(200) -> "200 OK";
status(201) -> "201 Created";
status(202) -> "202 Accepted";
status(203) -> "203 Non-Authoritative Information";
status(204) -> "204 No Content";
status(205) -> "205 Reset Content";
status(206) -> "206 Partial Content";
status(207) -> "207 Multi-Status";
status(226) -> "226 IM Used";
status(300) -> "300 Multiple Choices";
status(301) -> "301 Moved Permanently";
status(302) -> "302 Found";
status(303) -> "303 See Other";
status(304) -> "304 Not Modified";
status(305) -> "305 Use Proxy";
status(306) -> "306 Switch Proxy";
status(307) -> "307 Temporary Redirect";
status(400) -> "400 Bad Request";
status(401) -> "401 Unauthorized";
status(402) -> "402 Payment Required";
status(403) -> "403 Forbidden";
status(404) -> "404 Not Found";
status(405) -> "405 Method Not Allowed";
status(406) -> "406 Not Acceptable";
status(407) -> "407 Proxy Authentication Required";
status(408) -> "408 Request Timeout";
status(409) -> "409 Conflict";
status(410) -> "410 Gone";
status(411) -> "411 Length Required";
status(412) -> "412 Precondition Failed";
status(413) -> "413 Request Entity Too Large";
status(414) -> "414 Request-URI Too Long";
status(415) -> "415 Unsupported Media Type";
status(416) -> "416 Requested Range Not Satisfiable";
status(417) -> "417 Expectation Failed";
status(418) -> "418 I'm a teapot";
status(422) -> "422 Unprocessable Entity";
status(423) -> "423 Locked";
status(424) -> "424 Failed Dependency";
status(425) -> "425 Unordered Collection";
status(426) -> "426 Upgrade Required";
status(500) -> "500 Internal Server Error";
status(501) -> "501 Not Implemented";
status(502) -> "502 Bad Gateway";
status(503) -> "503 Service Unavailable";
status(504) -> "504 Gateway Timeout";
status(505) -> "505 HTTP Version Not Supported";
status(506) -> "506 Variant Also Negotiates";
status(507) -> "507 Insufficient Storage";
status(510) -> "510 Not Extended";
status(L) when is_list(L) -> L.
%% Tests. %% Tests.
-ifdef(TEST). -ifdef(TEST).