From 05c5378265275ddd01783e7f8c395575d3cc4e85 Mon Sep 17 00:00:00 2001 From: Zaiming Shi Date: Thu, 6 May 2021 17:59:33 +0200 Subject: [PATCH] feat(http_lib): add normalise_headers API --- src/emqx_http_lib.erl | 16 ++++++++++++++++ test/emqx_http_lib_tests.erl | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/src/emqx_http_lib.erl b/src/emqx_http_lib.erl index 9e86fe394..60f19e6bb 100644 --- a/src/emqx_http_lib.erl +++ b/src/emqx_http_lib.erl @@ -19,6 +19,7 @@ -export([ uri_encode/1 , uri_decode/1 , uri_parse/1 + , normalise_headers/1 ]). -export_type([uri_map/0]). @@ -91,6 +92,21 @@ do_parse(URI) -> normalise_parse_result(Map2) 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) -> Scheme = atom_scheme(Scheme0), DefaultPort = case https =:= Scheme of diff --git a/test/emqx_http_lib_tests.erl b/test/emqx_http_lib_tests.erl index 393d1ff86..a850da8f5 100644 --- a/test/emqx_http_lib_tests.erl +++ b/test/emqx_http_lib_tests.erl @@ -77,3 +77,8 @@ uri_parse_test_() -> end } ]. + +normalise_headers_test() -> + ?assertEqual([{"content-type", "applicaiton/binary"}], + emqx_http_lib:normalise_headers([{"Content_Type", "applicaiton/binary"}, + {"content-type", "applicaiton/json"}])).