Use the REST handler instead of the default one.
This makes the code simpler and more manageable.main
parent
03b76bddf2
commit
8f7481d785
|
@ -24,7 +24,9 @@ else is considered a bad request, apart from the obvious case of 500
|
|||
|
||||
-behaviour(cowboy_handler).
|
||||
|
||||
-export([init/2, terminate/3]).
|
||||
-export([init/2, terminate/3, allowed_methods/2,
|
||||
content_types_provided/2, known_methods/2,
|
||||
resource_exists/2, send_body/2]).
|
||||
|
||||
-include_lib("storage/include/storage.hrl").
|
||||
|
||||
|
@ -33,57 +35,27 @@ else is considered a bad request, apart from the obvious case of 500
|
|||
%
|
||||
|
||||
init(Req, State) ->
|
||||
{cowboy_rest, Req, State}.
|
||||
|
||||
allowed_methods(Req, State) ->
|
||||
{[<<"GET">>], Req, State}.
|
||||
|
||||
content_types_provided(Req, State) ->
|
||||
{[{{'*'}, send_body}], Req, State}.
|
||||
|
||||
known_methods(Req, State) ->
|
||||
{[<<"GET">>], Req, State}.
|
||||
|
||||
resource_exists(Req, State) ->
|
||||
{ok, Bucket} = maps:find(bucket, State),
|
||||
Path = cowboy_req:path(Req),
|
||||
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> ->
|
||||
%
|
||||
% Fetch the page from storage
|
||||
%
|
||||
case storage:read(Bucket, Path) of
|
||||
{ok, []} ->
|
||||
Resp = cowboy_req:reply(404,
|
||||
#{<<"content-type">> => <<"text/plain">>}, <<"Not found">>, Req),
|
||||
{ok, Resp, State};
|
||||
%
|
||||
% If we get a resource, send it back to the client with
|
||||
% it's proper mime type.
|
||||
%
|
||||
{ok, [R]} ->
|
||||
{Mime, Bin} = get_final_object(R),
|
||||
Resp = cowboy_req:reply(200, #{<<"content-type">> => Mime},
|
||||
Bin, Req),
|
||||
{ok, Resp, State};
|
||||
{error, _} ->
|
||||
Resp = cowboy_req:reply(500, #{<<"content-type">> => <<"text/plain">>},
|
||||
<<"Internal server error">>, Req),
|
||||
{ok, Resp, State}
|
||||
end;
|
||||
_ ->
|
||||
Resp = cowboy_req:reply(400, #{<<"content-type">> => <<"text/plain">>},
|
||||
<<"Bad request">>, Req),
|
||||
{ok, Resp, State}
|
||||
{ok, [R]} -> {true, Req, R};
|
||||
_ -> {false, Req, []}
|
||||
end.
|
||||
|
||||
send_body(Req, Record) ->
|
||||
{Record#object.value, Req, '_'}.
|
||||
|
||||
terminate(_Reason, _Req, _State) -> ok.
|
||||
|
||||
-spec get_final_object(Record) -> {Mime, Bin} when
|
||||
Record :: storage:object(),
|
||||
Mime :: binary(),
|
||||
Bin :: binary().
|
||||
|
||||
get_final_object(Record) ->
|
||||
case lists:keyfind(mime, 1, Record#object.metadata) of
|
||||
%
|
||||
% We do not know the object mime type. This should never
|
||||
% happen.
|
||||
%
|
||||
false ->
|
||||
{<<"application/octect-stream">>, Record#object.value};
|
||||
%
|
||||
% Everything else, just return it as is.
|
||||
%
|
||||
{mime, Mime} ->
|
||||
{list_to_binary(Mime), Record#object.value}
|
||||
end.
|
Loading…
Reference in New Issue