diff --git a/examples/example_openapi/src/example_file_api.erl b/examples/example_openapi/src/example_file_api.erl index 3c1e6fe..9ae91a3 100644 --- a/examples/example_openapi/src/example_file_api.erl +++ b/examples/example_openapi/src/example_file_api.erl @@ -1,4 +1,4 @@ -%% Copyright (c) 2013-2021 EMQ Technologies Co., Ltd. All Rights Reserved. +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License. diff --git a/src/body_encoder/minirest_binary_encoder.erl b/src/body_encoder/minirest_binary_encoder.erl new file mode 100644 index 0000000..2ea09aa --- /dev/null +++ b/src/body_encoder/minirest_binary_encoder.erl @@ -0,0 +1,22 @@ +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. + +-module(minirest_binary_encoder). + +-include("minirest_http.hrl"). + +-export([encode/1]). + +encode(Body) -> + {ok, maps:merge(?DEFAULT_RESPONSE_HEADERS, #{<<"content-length">> => erlang:size(Body)}), Body}. diff --git a/src/body_encoder/minirest_body_encoder.erl b/src/body_encoder/minirest_body_encoder.erl new file mode 100644 index 0000000..14b9670 --- /dev/null +++ b/src/body_encoder/minirest_body_encoder.erl @@ -0,0 +1,37 @@ +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. + +-module(minirest_body_encoder). + +-include("minirest_http.hrl"). +-export([ file_content_type_headers/1 + , file_content_type_headers/2 + ]). + +%% file content type +file_content_type_headers(Path) -> + file_content_type_headers(Path, #{return_type => map}). + +file_content_type_headers(Path, #{return_type := RT}) -> + FileType = filename:extension(Path), + case {maps:get(FileType, ?FILE_CONTENT_TYPE_MAP, undefined), RT} of + {undefined, map} -> + #{}; + {undefined, prop_list} -> + []; + {Type, map} -> + #{<<"content-type">> => Type}; + {Type, prop_list} -> + [{<<"content-type">>, Type}] + end. diff --git a/src/body_encoder/minirest_file_encoder.erl b/src/body_encoder/minirest_file_encoder.erl new file mode 100644 index 0000000..2cf003d --- /dev/null +++ b/src/body_encoder/minirest_file_encoder.erl @@ -0,0 +1,37 @@ +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. + +-module(minirest_file_encoder). + +-include("minirest_http.hrl"). +-include_lib("kernel/include/file.hrl"). + +-export([encode/1]). + +encode({file, Path}) -> + case filelib:is_file(Path) andalso file:read_file_info(Path) of + {ok, #file_info{size = Size}} -> + FileTypeContentTypeHeaders = minirest_body_encoder:file_content_type_headers(Path), + {ok, FileTypeContentTypeHeaders, {sendfile, 0, Size, Path}}; + {error, Reason} -> + Body = io_lib:format("mini rest file api bad return ~p", [Reason]), + {?RESPONSE_CODE_INTERNAL_SERVER_ERROR, #{<<"content-type">> => <<"text/plain">>}, Body}; + false -> + Body = io_lib:format("mini rest file api bad return ~p", [{bad_file, Path}]), + {?RESPONSE_CODE_INTERNAL_SERVER_ERROR, #{<<"content-type">> => <<"text/plain">>}, Body} + end; + +%% binary file content +encode({file_binary, FileName, Binary}) -> + {ok, minirest_body_encoder:file_content_type_headers(FileName), Binary}. diff --git a/src/body_encoder/minirest_form_data_encoder.erl b/src/body_encoder/minirest_form_data_encoder.erl new file mode 100644 index 0000000..6aa68d7 --- /dev/null +++ b/src/body_encoder/minirest_form_data_encoder.erl @@ -0,0 +1,125 @@ +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. + +-module(minirest_form_data_encoder). + +-include("minirest_http.hrl"). + +-export([encode/1]). + +encode({form_data, Data}) when is_list(Data) -> + case loop_encode(Data, boundary(), []) of + {response, Response} -> + {response, Response}; + {ok, Headers, <<"\r\n", RealBodyBinary/binary>>} -> + %% remove \r\n for first part + {ok, Headers, RealBodyBinary} + end; +encode({form_data, Data}) -> + Response = { + ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, + #{<<"content-type">> => <<"text/plain">>}, + list_to_binary(io_lib:format("invalid form-data term: ~p", [Data])) + }, + {response, Response}. + +loop_encode([], Boundary, Res) -> + Headers = #{<<"content-type">> => <<"multipart/form-data, boundary=", Boundary/binary>>}, + {ok, Headers, iolist_to_binary(lists:reverse(Res))}; + +loop_encode([Part | Tail], Boundary, Res) -> + case form_data_part(Part, Boundary) of + {response, Response} -> + {response, Response}; + PartBinary -> + loop_encode(Tail, Boundary, [PartBinary | Res]) + end. + +%% form-data file by path +form_data_part({Key, {file, Path}}, Boundary) -> + case filelib:is_file(Path) andalso file:read_file_info(Path) of + {ok, _} -> + case file:read_file(Path) of + {ok, Binary} -> + FileName = filename:basename(Path), + form_data_part({Key, {file_binary, FileName, Binary}}, Boundary); + {error, Reason} -> + error_form_data_response({read_file, {Path, Reason}}) + end; + {error, Reason} -> + error_form_data_response({bad_file, {Path, Reason}}); + false -> + error_form_data_response({bad_file, Path}) + end; + +%% form-data send file by binary +form_data_part({Key, {file_binary, FileName, FileBinary}}, Boundary) -> + case {to_binary(Key), to_binary(FileName)} of + {{error, KeyError}, {error, FileNameError}} -> + error_form_data_response({bad_file_part, {KeyError, FileNameError}}); + {{error, KeyError}, _} -> + error_form_data_response({bad_file_part, KeyError}); + {_, {error, FileNameError}} -> + error_form_data_response({bad_file_part, FileNameError}); + {KeyBinary, FileNameBinary} -> + FileHeaders = minirest_body_encoder:file_content_type_headers( + FileName, #{return_type => prop_list}), + Headers = [ + {<<"Content-Disposition">>, + <<"form-data; name=\"", KeyBinary/binary, + "\"; filename=\"", FileNameBinary/binary, "\"">>} + | FileHeaders], + PartHeaders = cow_multipart:part(Boundary, Headers), + iolist_to_binary([PartHeaders, FileBinary]) + end; + +%% key & value +form_data_part({Key, Value}, Boundary) -> + case {to_binary(Key), to_binary(Value)} of + {{error, {not_support, Key}}, {error, {not_support, Value}}} -> + error_form_data_response({Key, Value}); + {{error, {not_support, Key}}, _} -> + error_form_data_response({bad_key, Key}); + {_, {error, {not_support, Value}}} -> + error_form_data_response({bad_value, Value}); + {KBinary, VBinary} -> + NHeaders = [ + {<<"content-disposition">>, <<"form-data; name=\"", KBinary/binary, "\"">>}, + {<<"content-type">>, <<"application/x-www-form-urlencoded">>}], + PartHeaders = cow_multipart:part(Boundary, NHeaders), + iolist_to_binary([PartHeaders, VBinary]) + end; + +form_data_part(NotSupport, _) -> + error_form_data_response({not_support, NotSupport}). + +error_form_data_response(Data) -> + Response = { + ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, + #{<<"content-type">> => <<"text/plain">>}, + list_to_binary(io_lib:format("invalid form-data term: ~p", [Data])) + }, + {response, Response}. + +boundary() -> + cow_multipart:boundary(). + +to_binary(Data) when is_binary(Data) -> Data; +to_binary(Data) when is_list(Data) -> list_to_binary(Data); +to_binary(Data) when is_atom(Data) -> atom_to_binary(Data, utf8); +to_binary(Data) when is_float(Data) -> float_to_binary(Data, [{decimals, 10}, compact]); +to_binary(Data) when is_integer(Data) -> integer_to_binary(Data); +to_binary(true) -> <<"true">>; +to_binary(false) -> <<"false">>; +to_binary(Data) -> {error, {not_support, Data}}. diff --git a/src/body_encoder/minirest_json_encoder.erl b/src/body_encoder/minirest_json_encoder.erl new file mode 100644 index 0000000..01cfcee --- /dev/null +++ b/src/body_encoder/minirest_json_encoder.erl @@ -0,0 +1,31 @@ +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. + +-module(minirest_json_encoder). +-include("minirest_http.hrl"). + +-export([encode/1]). + +encode(Body) -> + case jsx:is_term(Body) of + true -> + {ok, ?DEFAULT_RESPONSE_HEADERS, jsx:encode(Body)}; + false -> + Response = { + ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, + #{<<"content-type">> => <<"text/plain">>}, + list_to_binary(io_lib:format("invalid json term: ~p", [Body])) + }, + {response, Response} + end. diff --git a/src/body_encoder/minirest_message_encoder.erl b/src/body_encoder/minirest_message_encoder.erl new file mode 100644 index 0000000..7ba9b09 --- /dev/null +++ b/src/body_encoder/minirest_message_encoder.erl @@ -0,0 +1,154 @@ +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. +-module(minirest_message_encoder). + +-include("minirest_http.hrl"). + +-export([ encode/1 + , encode/2 + ]). + +encode(Message) -> + Config = #{depth => unlimited, single_line => true}, + encode(Message, Config). + +encode(Message, Config) -> + JsonReady = best_effort_json_obj(Message, Config), + jsx:encode(JsonReady). + +best_effort_json_obj(List, Config) when is_list(List) -> + try + json_obj(maps:from_list(List), Config) + catch + _:_ -> + [json(I, Config) || I <- List] + end; +best_effort_json_obj(Map, Config) -> + try + json_obj(Map, Config) + catch + _:_ -> + do_format_msg("~p", [Map], Config) + end. + +json_obj(Data, Config) -> + maps:fold(fun(K, V, D) -> json_kv(K, V, D, Config) end, maps:new(), Data). + +json_kv(mfa, {M, F, A}, Data, _Config) -> + maps:put( + mfa, + << + (atom_to_binary(M, utf8))/binary, + $:, + (atom_to_binary(F, utf8))/binary, + $/, + (integer_to_binary(A))/binary + >>, + Data + ); +%% snabbkaffe +json_kv('$kind', Kind, Data, Config) -> + maps:put(msg, json(Kind, Config), Data); +json_kv(gl, _, Data, _Config) -> + %% drop gl because it's not interesting + Data; +json_kv(file, _, Data, _Config) -> + %% drop 'file' because we have mfa + Data; +json_kv(K0, V, Data, Config) -> + K = json_key(K0), + case is_map(V) of + true -> maps:put(json(K, Config), best_effort_json_obj(V, Config), Data); + false -> maps:put(json(K, Config), json(V, Config), Data) + end. + +json_key(A) when is_atom(A) -> json_key(atom_to_binary(A, utf8)); +json_key(Term) -> + try unicode:characters_to_binary(Term, utf8) of + OK when is_binary(OK) andalso OK =/= <<>> -> + OK; + _ -> + throw({badkey, Term}) + catch + _:_ -> + throw({badkey, Term}) + end. + +json([], _) -> + "[]"; +json(<<"">>, _) -> + "\"\""; +json(A, _) when is_atom(A) -> atom_to_binary(A, utf8); +json(I, _) when is_integer(I) -> I; +json(F, _) when is_float(F) -> F; +json(P, C) when is_pid(P) -> json(pid_to_list(P), C); +json(P, C) when is_port(P) -> json(port_to_list(P), C); +json(F, C) when is_function(F) -> json(erlang:fun_to_list(F), C); +json(B, Config) when is_binary(B) -> + best_effort_unicode(B, Config); +json(L, Config) when is_list(L), is_integer(hd(L)) -> + best_effort_unicode(L, Config); +json(M, Config) when is_list(M), is_tuple(hd(M)), tuple_size(hd(M)) =:= 2 -> + best_effort_json_obj(M, Config); +json(L, Config) when is_list(L) -> + [json(I, Config) || I <- L]; +json(Map, Config) when is_map(Map) -> + best_effort_json_obj(Map, Config); +json(Term, Config) -> + do_format_msg("~p", [Term], Config). + +best_effort_unicode(Input, Config) -> + try unicode:characters_to_binary(Input, utf8) of + B when is_binary(B) -> B; + _ -> do_format_msg("~p", [Input], Config) + catch + _:_ -> + do_format_msg("~p", [Input], Config) + end. + +do_format_msg(Format0, Args, #{depth := Depth, single_line := SingleLine}) -> + Format1 = io_lib:scan_format(Format0, Args), + Format = reformat(Format1, Depth, SingleLine), + Text0 = io_lib:build_text(Format, []), + Text = + case SingleLine of + true -> re:replace(Text0, ",?\r?\n\s*", ", ", [{return, list}, global, unicode]); + false -> Text0 + end, + trim(unicode:characters_to_binary(Text, utf8)). + +%% Get rid of the leading spaces. +%% leave alone the trailing spaces. +trim(<<$\s, Rest/binary>>) -> trim(Rest); +trim(Bin) -> Bin. + +reformat(Format, unlimited, false) -> + Format; +reformat([#{control_char := C} = M | T], Depth, true) when C =:= $p -> + [limit_depth(M#{width => 0}, Depth) | reformat(T, Depth, true)]; +reformat([#{control_char := C} = M | T], Depth, true) when C =:= $P -> + [M#{width => 0} | reformat(T, Depth, true)]; +reformat([#{control_char := C} = M | T], Depth, Single) when C =:= $p; C =:= $w -> + [limit_depth(M, Depth) | reformat(T, Depth, Single)]; +reformat([H | T], Depth, Single) -> + [H | reformat(T, Depth, Single)]; +reformat([], _, _) -> + []. + +limit_depth(M0, unlimited) -> + M0; +limit_depth(#{control_char := C0, args := Args} = M0, Depth) -> + %To uppercase. + C = C0 - ($a - $A), + M0#{control_char := C, args := Args ++ [Depth]}. diff --git a/src/minirest.erl b/src/minirest.erl index b0dee16..63c4039 100644 --- a/src/minirest.erl +++ b/src/minirest.erl @@ -1,4 +1,4 @@ -%% Copyright (c) 2013-2021 EMQ Technologies Co., Ltd. All Rights Reserved. +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License. diff --git a/src/minirest_body.erl b/src/minirest_body.erl index 9996397..9601fe3 100644 --- a/src/minirest_body.erl +++ b/src/minirest_body.erl @@ -1,4 +1,4 @@ -%% Copyright (c) 2013-2021 EMQ Technologies Co., Ltd. All Rights Reserved. +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License. @@ -22,7 +22,8 @@ ]). -export([ encode/1 - , encode/2]). + , encode/2 + ]). %%============================================================================================== %% parse -spec(parse(Request :: map()) -> @@ -110,169 +111,18 @@ binary_decoder(Request, Acc) -> %%============================================================================================== %% internal %% encoder +%% too many encoder, so put them in minirest/body_encoder/x_encoder.erl encoder({file, _}) -> - fun file_encoder/1; + fun minirest_file_encoder:encode/1; encoder({file_binary, _, _}) -> - fun file_binary_encoder/1; + fun minirest_file_encoder:encode/1; encoder(Body) when is_binary(Body) -> - fun binary_encoder/1; + fun minirest_binary_encoder:encode/1; encoder(Body) when is_map(Body) -> - fun json_encoder/1; + fun minirest_json_encoder:encode/1; encoder(Body) when is_list(Body) -> - fun json_encoder/1; + fun minirest_json_encoder:encode/1; encoder({form_data, _}) -> - fun form_data_encoder/1. - - -file_encoder({file, Path}) -> - case filelib:is_file(Path) andalso file:read_file_info(Path) of - {ok, #file_info{size = Size}} -> - FileTypeContentTypeHeaders = file_content_type_headers(Path), - {ok, FileTypeContentTypeHeaders, {sendfile, 0, Size, Path}}; - {error, Reason} -> - Body = io_lib:format("mini rest file api bad return ~p", [Reason]), - {?RESPONSE_CODE_INTERNAL_SERVER_ERROR, #{<<"content-type">> => <<"text/plain">>}, Body}; - false -> - Body = io_lib:format("mini rest file api bad return ~p", [{bad_file, Path}]), - {?RESPONSE_CODE_INTERNAL_SERVER_ERROR, #{<<"content-type">> => <<"text/plain">>}, Body} - end. - -file_binary_encoder({file_binary, FileName, Binary}) -> - {ok, file_content_type_headers(FileName), Binary}. - -binary_encoder(Body) -> - {ok, maps:merge(?DEFAULT_RESPONSE_HEADERS, #{<<"content-length">> => erlang:size(Body)}), Body}. - -json_encoder(Body) -> - case jsx:is_term(Body) of - true -> - {ok, ?DEFAULT_RESPONSE_HEADERS, jsx:encode(Body)}; - false -> - Response = { - ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, - #{<<"content-type">> => <<"text/plain">>}, - list_to_binary(io_lib:format("invalid json term: ~p", [Body])) - }, - {response, Response} - end. - -form_data_encoder({form_data, Data}) when is_list(Data) -> - case form_data_loop_encoder(Data, boundary(), []) of - {response, Response} -> - {response, Response}; - {ok, Headers, <<"\r\n", RealBodyBinary/binary>>} -> - %% remove \r\n for first part - {ok, Headers, RealBodyBinary} - end; -form_data_encoder({form_data, Data}) -> - Response = { - ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, - #{<<"content-type">> => <<"text/plain">>}, - list_to_binary(io_lib:format("invalid form-data term: ~p", [Data])) - }, - {response, Response}. - -form_data_loop_encoder([], Boundary, Res) -> - Headers = #{<<"content-type">> => <<"multipart/form-data, boundary=", Boundary/binary>>}, - {ok, Headers, iolist_to_binary(lists:reverse(Res))}; - -form_data_loop_encoder([Part | Tail], Boundary, Res) -> - case form_data_part(Part, Boundary) of - {response, Response} -> - {response, Response}; - PartBinary -> - form_data_loop_encoder(Tail, Boundary, [PartBinary | Res]) - end. - -%% form-data file by path -form_data_part({Key, {file, Path}}, Boundary) -> - case filelib:is_file(Path) andalso file:read_file_info(Path) of - {ok, _} -> - case file:read_file(Path) of - {ok, Binary} -> - FileName = filename:basename(Path), - form_data_part({Key, {file_binary, FileName, Binary}}, Boundary); - {error, Reason} -> - error_form_data_response({read_file, {Path, Reason}}) - end; - {error, Reason} -> - error_form_data_response({bad_file, {Path, Reason}}); - false -> - error_form_data_response({bad_file, Path}) - end; - -%% form-data send file by binary -form_data_part({Key, {file_binary, FileName, FileBinary}}, Boundary) -> - case {to_binary(Key), to_binary(FileName)} of - {{error, KeyError}, {error, FileNameError}} -> - error_form_data_response({bad_file_part, {KeyError, FileNameError}}); - {{error, KeyError}, _} -> - error_form_data_response({bad_file_part, KeyError}); - {_, {error, FileNameError}} -> - error_form_data_response({bad_file_part, FileNameError}); - {KeyBinary, FileNameBinary} -> - Headers = [ - {<<"Content-Disposition">>, - <<"form-data; name=\"", KeyBinary/binary, - "\"; filename=\"", FileNameBinary/binary, "\"">>} - | file_content_type_headers(FileName, #{return_type => prop_list})], - PartHeaders = cow_multipart:part(Boundary, Headers), - iolist_to_binary([PartHeaders, FileBinary]) - end; - -%% key & value -form_data_part({Key, Value}, Boundary) -> - case {to_binary(Key), to_binary(Value)} of - {{error, {not_support, Key}}, {error, {not_support, Value}}} -> - error_form_data_response({Key, Value}); - {{error, {not_support, Key}}, _} -> - error_form_data_response({bad_key, Key}); - {_, {error, {not_support, Value}}} -> - error_form_data_response({bad_value, Value}); - {KBinary, VBinary} -> - NHeaders = [ - {<<"content-disposition">>, <<"form-data; name=\"", KBinary/binary, "\"">>}, - {<<"content-type">>, <<"application/x-www-form-urlencoded">>}], - PartHeaders = cow_multipart:part(Boundary, NHeaders), - iolist_to_binary([PartHeaders, VBinary]) - end; - -form_data_part(NotSupport, _) -> - error_form_data_response({not_support, NotSupport}). - -%% file content type -file_content_type_headers(Path) -> - file_content_type_headers(Path, #{return_type => map}). - -file_content_type_headers(Path, #{return_type := RT}) -> - FileType = filename:extension(Path), - case {maps:get(FileType, ?FILE_CONTENT_TYPE_MAP, undefined), RT} of - {undefined, map} -> - #{}; - {undefined, prop_list} -> - []; - {Type, map} -> - #{<<"content-type">> => Type}; - {Type, prop_list} -> - [{<<"content-type">>, Type}] - end. - -error_form_data_response(Data) -> - Response = { - ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, - #{<<"content-type">> => <<"text/plain">>}, - list_to_binary(io_lib:format("invalid form-data term: ~p", [Data])) - }, - {response, Response}. - -boundary() -> - cow_multipart:boundary(). - -to_binary(Data) when is_binary(Data) -> Data; -to_binary(Data) when is_list(Data) -> list_to_binary(Data); -to_binary(Data) when is_atom(Data) -> atom_to_binary(Data, utf8); -to_binary(Data) when is_float(Data) -> float_to_binary(Data, [{decimals, 10}, compact]); -to_binary(Data) when is_integer(Data) -> integer_to_binary(Data); -to_binary(true) -> <<"true">>; -to_binary(false) -> <<"false">>; -to_binary(Data) -> {error, {not_support, Data}}. + fun minirest_form_data_encoder:encode/1; +encoder({message, _}) -> + fun minirest_message_encoder:encode/1. diff --git a/src/minirest_handler.erl b/src/minirest_handler.erl index 0036956..593c74b 100644 --- a/src/minirest_handler.erl +++ b/src/minirest_handler.erl @@ -1,4 +1,4 @@ -%% Copyright (c) 2013-2021 EMQ Technologies Co., Ltd. All Rights Reserved. +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License. @@ -116,16 +116,15 @@ apply_callback(Request, Params, Handler) -> %% response error reply({ErrorStatus, #{code := Code, message := Message}}, Req, Handler) when (ErrorStatus < 200 orelse 300 =< ErrorStatus) - andalso is_atom(Code) - andalso is_binary(Message) -> + andalso is_atom(Code) -> reply({ErrorStatus, Code, Message}, Req, Handler); reply({ErrorStatus, Code, Message}, Req, Handler = #handler{error_codes = Codes}) when (ErrorStatus < 200 orelse 300 =< ErrorStatus) - andalso is_atom(Code) - andalso is_binary(Message) -> + andalso is_atom(Code) -> case maybe_ignore_code_check(ErrorStatus, Code) orelse lists:member(Code, Codes) of true -> - {ok, Headers, Body} = minirest_body:encode(#{code => Code, message => Message}), + ErrorMessageStruct = {message, #{code => Code, message => Message}}, + {ok, Headers, Body} = minirest_body:encode(ErrorMessageStruct), reply({ErrorStatus, Headers, Body}, Req, Handler); false -> Message = diff --git a/src/minirest_info_api.erl b/src/minirest_info_api.erl index 236714f..e094770 100644 --- a/src/minirest_info_api.erl +++ b/src/minirest_info_api.erl @@ -1,4 +1,4 @@ -%% Copyright (c) 2013-2021 EMQ Technologies Co., Ltd. All Rights Reserved. +%% Copyright (c) 2013-2022 EMQ Technologies Co., Ltd. All Rights Reserved. %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License.