feat(http_lib): add normalise_headers API

This commit is contained in:
Zaiming Shi 2021-05-06 17:59:33 +02:00 committed by turtleDeng
parent 323c1a4896
commit 05c5378265
2 changed files with 21 additions and 0 deletions

View File

@ -19,6 +19,7 @@
-export([ uri_encode/1 -export([ uri_encode/1
, uri_decode/1 , uri_decode/1
, uri_parse/1 , uri_parse/1
, normalise_headers/1
]). ]).
-export_type([uri_map/0]). -export_type([uri_map/0]).
@ -91,6 +92,21 @@ do_parse(URI) ->
normalise_parse_result(Map2) normalise_parse_result(Map2)
end. end.
%% @doc Return HTTP headers list with keys lower-cased and
%% underscores replaced with hyphens
%% NOTE: assuming the input Headers list is a proplists,
%% that is, when a key is duplicated, list header overrides tail
%% e.g. [{"Content_Type", "applicaiton/binary"}, {"content-type", "applicaiton/json"}]
%% results in: [{"content-type", "applicaiton/binary"}]
normalise_headers(Headers0) ->
F = fun({K0, V}) ->
K = re:replace(K0, "_", "-", [{return,list}]),
{string:lowercase(K), V}
end,
Headers = lists:map(F, Headers0),
Keys = proplists:get_keys(Headers),
[{K, proplists:get_value(K, Headers)} || K <- Keys].
normalise_parse_result(#{host := Host, scheme := Scheme0} = Map) -> normalise_parse_result(#{host := Host, scheme := Scheme0} = Map) ->
Scheme = atom_scheme(Scheme0), Scheme = atom_scheme(Scheme0),
DefaultPort = case https =:= Scheme of DefaultPort = case https =:= Scheme of

View File

@ -77,3 +77,8 @@ uri_parse_test_() ->
end end
} }
]. ].
normalise_headers_test() ->
?assertEqual([{"content-type", "applicaiton/binary"}],
emqx_http_lib:normalise_headers([{"Content_Type", "applicaiton/binary"},
{"content-type", "applicaiton/json"}])).