From 056d26b4d8d65f9bd83c594f307602eac5f2312a Mon Sep 17 00:00:00 2001 From: Andrei Nesterov Date: Sun, 6 Mar 2016 20:14:43 +0300 Subject: Add cow_http_hd:access_control_allow_origin/1 --- src/cow_http_hd.erl | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'src') diff --git a/src/cow_http_hd.erl b/src/cow_http_hd.erl index 80a2f8a..8e258f9 100644 --- a/src/cow_http_hd.erl +++ b/src/cow_http_hd.erl @@ -115,6 +115,7 @@ -export([access_control_allow_credentials/0]). -export([access_control_allow_headers/1]). -export([access_control_allow_methods/1]). +-export([access_control_allow_origin/1]). -type etag() :: {weak | strong, binary()}. -export_type([etag/0]). @@ -3280,6 +3281,40 @@ horse_access_control_allow_methods() -> ). -endif. +%% @doc Build the Access-Control-Allow-Origin header. + +-spec access_control_allow_origin({binary(), binary(), 0..65535} | reference() | '*') -> iodata(). +access_control_allow_origin({Scheme, Host, Port}) -> + case default_port(Scheme) of + Port -> [Scheme, <<"://">>, Host]; + _ -> [Scheme, <<"://">>, Host, <<":">>, integer_to_binary(Port)] + end; +access_control_allow_origin('*') -> <<$*>>; +access_control_allow_origin(Ref) when is_reference(Ref) -> <<"null">>. + +-ifdef(TEST). +access_control_allow_origin_test_() -> + Tests = [ + {{<<"http">>, <<"www.example.org">>, 8080}, <<"http://www.example.org:8080">>}, + {{<<"http">>, <<"www.example.org">>, 80}, <<"http://www.example.org">>}, + {{<<"http">>, <<"192.0.2.1">>, 8080}, <<"http://192.0.2.1:8080">>}, + {{<<"http">>, <<"192.0.2.1">>, 80}, <<"http://192.0.2.1">>}, + {{<<"http">>, <<"[2001:db8::1]">>, 8080}, <<"http://[2001:db8::1]:8080">>}, + {{<<"http">>, <<"[2001:db8::1]">>, 80}, <<"http://[2001:db8::1]">>}, + {{<<"http">>, <<"[::ffff:192.0.2.1]">>, 8080}, <<"http://[::ffff:192.0.2.1]:8080">>}, + {{<<"http">>, <<"[::ffff:192.0.2.1]">>, 80}, <<"http://[::ffff:192.0.2.1]">>}, + {make_ref(), <<"null">>}, + {'*', <<$*>>} + ], + [{lists:flatten(io_lib:format("~p", [V])), + fun() -> R = iolist_to_binary(access_control_allow_origin(V)) end} || {V, R} <- Tests]. + +horse_access_control_allow_origin() -> + horse:repeat(200000, + access_control_allow_origin({<<"http">>, <<"example.org">>, 8080}) + ). +-endif. + %% Internal. %% Only return if the list is not empty. -- cgit v1.2.3