cowboy_dispatcher.erl 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(cowboy_dispatcher).
  15. -export([split_host/1, split_path/1, match/3]). %% API.
  16. -include("include/types.hrl").
  17. -include_lib("eunit/include/eunit.hrl").
  18. %% API.
  19. -spec split_host(Host::string()) -> Tokens::path_tokens().
  20. split_host(Host) ->
  21. Host2 = case string:chr(Host, $:) of
  22. 0 -> Host;
  23. N -> lists:sublist(Host, N - 1)
  24. end,
  25. string:tokens(Host2, ".").
  26. -spec split_path(Path::string())
  27. -> {Tokens::path_tokens(), Path::string(), Qs::string()}.
  28. split_path(Path) ->
  29. case string:chr(Path, $?) of
  30. 0 ->
  31. {string:tokens(Path, "/"), Path, []};
  32. N ->
  33. {Path2, [$?|Qs]} = lists:split(N - 1, Path),
  34. {string:tokens(Path2, "/"), Path2, Qs}
  35. end.
  36. -spec match(Host::path_tokens(), Path::path_tokens(),
  37. Dispatch::dispatch_rules())
  38. -> {ok, Handler::module(), Opts::term(), Binds::bindings()}
  39. | {error, notfound, host} | {error, notfound, path}.
  40. match(_Host, _Path, []) ->
  41. {error, notfound, host};
  42. match(_Host, Path, [{'_', PathMatchs}|_Tail]) ->
  43. match_path(Path, PathMatchs, []);
  44. match(Host, Path, [{HostMatch, PathMatchs}|Tail]) ->
  45. case try_match(host, Host, HostMatch) of
  46. false ->
  47. match(Host, Path, Tail);
  48. {true, HostBinds} ->
  49. match_path(Path, PathMatchs, HostBinds)
  50. end.
  51. -spec match_path(Path::path_tokens(), list({Path::match(),
  52. Handler::module(), Opts::term()}), HostBinds::bindings())
  53. -> {ok, Handler::module(), Opts::term(), Binds::bindings()}
  54. | {error, notfound, path}.
  55. match_path(_Path, [], _HostBinds) ->
  56. {error, notfound, path};
  57. match_path(_Path, [{'_', Handler, Opts}|_Tail], HostBinds) ->
  58. {ok, Handler, Opts, HostBinds};
  59. match_path('*', [{'*', Handler, Opts}|_Tail], HostBinds) ->
  60. {ok, Handler, Opts, HostBinds};
  61. match_path(Path, [{PathMatch, Handler, Opts}|Tail], HostBinds) ->
  62. case try_match(path, Path, PathMatch) of
  63. false ->
  64. match_path(Path, Tail, HostBinds);
  65. {true, PathBinds} ->
  66. {ok, Handler, Opts, HostBinds ++ PathBinds}
  67. end.
  68. %% Internal.
  69. -spec try_match(Type::host | path, List::path_tokens(), Match::match())
  70. -> {true, Binds::bindings()} | false.
  71. try_match(_Type, _List, '_') ->
  72. {true, []};
  73. try_match(_Type, List, Match) when length(List) =/= length(Match) ->
  74. false;
  75. try_match(host, List, Match) ->
  76. list_match(lists:reverse(List), lists:reverse(Match), []);
  77. try_match(path, List, Match) ->
  78. list_match(List, Match, []).
  79. -spec list_match(List::path_tokens(), Match::match(), Binds::bindings())
  80. -> {true, Binds::bindings()} | false.
  81. %% Atom '_' matches anything, continue.
  82. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  83. list_match(Tail, TailMatch, Binds);
  84. %% Both values match, continue.
  85. list_match([E|Tail], [E|TailMatch], Binds) ->
  86. list_match(Tail, TailMatch, Binds);
  87. %% Bind E to the variable name V and continue.
  88. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  89. list_match(Tail, TailMatch, [{V, E}|Binds]);
  90. %% Values don't match, stop.
  91. list_match([_E|_Tail], [_F|_TailMatch], _Binds) ->
  92. false;
  93. %% Match complete.
  94. list_match([], [], Binds) ->
  95. {true, Binds}.
  96. %% Tests.
  97. -ifdef(TEST).
  98. split_host_test_() ->
  99. %% {Host, Result}
  100. Tests = [
  101. {"", []},
  102. {".........", []},
  103. {"*", ["*"]},
  104. {"cowboy.dev-extend.eu", ["cowboy", "dev-extend", "eu"]},
  105. {"dev-extend..eu", ["dev-extend", "eu"]},
  106. {"dev-extend.eu", ["dev-extend", "eu"]},
  107. {"dev-extend.eu:8080", ["dev-extend", "eu"]},
  108. {"a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z",
  109. ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
  110. "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]}
  111. ],
  112. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  113. split_path_test_() ->
  114. %% {Path, Result, QueryString}
  115. Tests = [
  116. {"?", [], "", ""},
  117. {"???", [], "", "??"},
  118. {"/", [], "/", ""},
  119. {"/users", ["users"], "/users", ""},
  120. {"/users?", ["users"], "/users", ""},
  121. {"/users?a", ["users"], "/users", "a"},
  122. {"/users/42/friends?a=b&c=d&e=notsure?whatever",
  123. ["users", "42", "friends"],
  124. "/users/42/friends", "a=b&c=d&e=notsure?whatever"}
  125. ],
  126. [{P, fun() -> {R, RawP, Qs} = split_path(P) end} || {P, R, RawP, Qs} <- Tests].
  127. match_test_() ->
  128. Dispatch = [
  129. {["www", '_', "dev-extend", "eu"], [
  130. {["users", '_', "mails"], match_any_subdomain_users, []}
  131. ]},
  132. {["dev-extend", "eu"], [
  133. {["users", id, "friends"], match_extend_users_friends, []},
  134. {'_', match_extend, []}
  135. ]},
  136. {["dev-extend", var], [
  137. {["threads", var], match_duplicate_vars,
  138. [we, {expect, two}, var, here]}
  139. ]},
  140. {["erlang", ext], [
  141. {'_', match_erlang_ext, []}
  142. ]},
  143. {'_', [
  144. {["users", id, "friends"], match_users_friends, []},
  145. {'_', match_any, []}
  146. ]}
  147. ],
  148. %% {Host, Path, Result}
  149. Tests = [
  150. {["any"], [], {ok, match_any, [], []}},
  151. {["www", "any", "dev-extend", "eu"], ["users", "42", "mails"],
  152. {ok, match_any_subdomain_users, [], []}},
  153. {["www", "dev-extend", "eu"], ["users", "42", "mails"],
  154. {ok, match_any, [], []}},
  155. {["www", "dev-extend", "eu"], [], {ok, match_any, [], []}},
  156. {["www", "any", "dev-extend", "eu"], ["not_users", "42", "mails"],
  157. {error, notfound, path}},
  158. {["dev-extend", "eu"], [], {ok, match_extend, [], []}},
  159. {["dev-extend", "eu"], ["users", "42", "friends"],
  160. {ok, match_extend_users_friends, [], [{id, "42"}]}},
  161. {["erlang", "fr"], '_', {ok, match_erlang_ext, [], [{ext, "fr"}]}},
  162. {["any"], ["users", "444", "friends"],
  163. {ok, match_users_friends, [], [{id, "444"}]}},
  164. {["dev-extend", "fr"], ["threads", "987"],
  165. {ok, match_duplicate_vars, [we, {expect, two}, var, here],
  166. [{var, "fr"}, {var, "987"}]}}
  167. ],
  168. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  169. R = match(H, P, Dispatch)
  170. end} || {H, P, R} <- Tests].
  171. -endif.