cowboy_dispatcher.erl 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.eu>
  2. %% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. -module(cowboy_dispatcher).
  16. -export([split_host/1, split_path/1, match/3]). %% API.
  17. -type bindings() :: list({atom(), binary()}).
  18. -type path_tokens() :: list(binary()).
  19. -type match_rule() :: '_' | '*' | list(binary() | '_' | atom()).
  20. -type dispatch_path() :: list({match_rule(), module(), any()}).
  21. -type dispatch_rule() :: {Host::match_rule(), Path::dispatch_path()}.
  22. -type dispatch_rules() :: list(dispatch_rule()).
  23. -export_type([bindings/0, path_tokens/0, dispatch_rules/0]).
  24. -include_lib("eunit/include/eunit.hrl").
  25. %% API.
  26. -spec split_host(binary())
  27. -> {path_tokens(), binary(), undefined | inet:ip_port()}.
  28. split_host(<<>>) ->
  29. {[], <<>>, undefined};
  30. split_host(Host) ->
  31. case binary:split(Host, <<":">>) of
  32. [Host] ->
  33. {binary:split(Host, <<".">>, [global, trim]), Host, undefined};
  34. [Host2, Port] ->
  35. {binary:split(Host2, <<".">>, [global, trim]), Host2,
  36. list_to_integer(binary_to_list(Port))}
  37. end.
  38. -spec split_path(binary()) -> {path_tokens(), binary(), binary()}.
  39. split_path(Path) ->
  40. case binary:split(Path, <<"?">>) of
  41. [Path] -> {do_split_path(Path, <<"/">>), Path, <<>>};
  42. [<<>>, Qs] -> {[], <<>>, Qs};
  43. [Path2, Qs] -> {do_split_path(Path2, <<"/">>), Path2, Qs}
  44. end.
  45. -spec do_split_path(binary(), <<_:8>>) -> path_tokens().
  46. do_split_path(RawPath, Separator) ->
  47. case binary:split(RawPath, Separator, [global, trim]) of
  48. [<<>>|Path] -> Path;
  49. Path -> Path
  50. end.
  51. -spec match(Host::path_tokens(), Path::path_tokens(), dispatch_rules())
  52. -> {ok, module(), any(), bindings(),
  53. HostInfo::undefined | path_tokens(),
  54. PathInfo::undefined | path_tokens()}
  55. | {error, notfound, host} | {error, notfound, path}.
  56. match(_Host, _Path, []) ->
  57. {error, notfound, host};
  58. match(_Host, Path, [{'_', PathMatchs}|_Tail]) ->
  59. match_path(Path, PathMatchs, [], undefined);
  60. match(Host, Path, [{HostMatch, PathMatchs}|Tail]) ->
  61. case try_match(host, Host, HostMatch) of
  62. false ->
  63. match(Host, Path, Tail);
  64. {true, HostBinds, undefined} ->
  65. match_path(Path, PathMatchs, HostBinds, undefined);
  66. {true, HostBinds, HostInfo} ->
  67. match_path(Path, PathMatchs, HostBinds, lists:reverse(HostInfo))
  68. end.
  69. -spec match_path(path_tokens(), dispatch_path(), bindings(),
  70. HostInfo::undefined | path_tokens())
  71. -> {ok, module(), any(), bindings(),
  72. HostInfo::undefined | path_tokens(),
  73. PathInfo::undefined | path_tokens()}
  74. | {error, notfound, path}.
  75. match_path(_Path, [], _HostBinds, _HostInfo) ->
  76. {error, notfound, path};
  77. match_path(_Path, [{'_', Handler, Opts}|_Tail], HostBinds, HostInfo) ->
  78. {ok, Handler, Opts, HostBinds, HostInfo, undefined};
  79. match_path('*', [{'*', Handler, Opts}|_Tail], HostBinds, HostInfo) ->
  80. {ok, Handler, Opts, HostBinds, HostInfo, undefined};
  81. match_path(Path, [{PathMatch, Handler, Opts}|Tail], HostBinds, HostInfo) ->
  82. case try_match(path, Path, PathMatch) of
  83. false ->
  84. match_path(Path, Tail, HostBinds, HostInfo);
  85. {true, PathBinds, PathInfo} ->
  86. {ok, Handler, Opts, HostBinds ++ PathBinds, HostInfo, PathInfo}
  87. end.
  88. %% Internal.
  89. -spec try_match(host | path, path_tokens(), match_rule())
  90. -> {true, bindings(), undefined | path_tokens()} | false.
  91. try_match(host, List, Match) ->
  92. list_match(lists:reverse(List), lists:reverse(Match), []);
  93. try_match(path, List, Match) ->
  94. list_match(List, Match, []).
  95. -spec list_match(path_tokens(), match_rule(), bindings())
  96. -> {true, bindings(), undefined | path_tokens()} | false.
  97. %% Atom '...' matches any trailing path, stop right now.
  98. list_match(List, ['...'], Binds) ->
  99. {true, Binds, List};
  100. %% Atom '_' matches anything, continue.
  101. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  102. list_match(Tail, TailMatch, Binds);
  103. %% Both values match, continue.
  104. list_match([E|Tail], [E|TailMatch], Binds) ->
  105. list_match(Tail, TailMatch, Binds);
  106. %% Bind E to the variable name V and continue.
  107. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  108. list_match(Tail, TailMatch, [{V, E}|Binds]);
  109. %% Match complete.
  110. list_match([], [], Binds) ->
  111. {true, Binds, undefined};
  112. %% Values don't match, stop.
  113. list_match(_List, _Match, _Binds) ->
  114. false.
  115. %% Tests.
  116. -ifdef(TEST).
  117. split_host_test_() ->
  118. %% {Host, Result}
  119. Tests = [
  120. {<<"">>, {[], <<"">>, undefined}},
  121. {<<".........">>, {[], <<".........">>, undefined}},
  122. {<<"*">>, {[<<"*">>], <<"*">>, undefined}},
  123. {<<"cowboy.dev-extend.eu">>,
  124. {[<<"cowboy">>, <<"dev-extend">>, <<"eu">>],
  125. <<"cowboy.dev-extend.eu">>, undefined}},
  126. {<<"dev-extend..eu">>,
  127. {[<<"dev-extend">>, <<>>, <<"eu">>],
  128. <<"dev-extend..eu">>, undefined}},
  129. {<<"dev-extend.eu">>,
  130. {[<<"dev-extend">>, <<"eu">>], <<"dev-extend.eu">>, undefined}},
  131. {<<"dev-extend.eu:8080">>,
  132. {[<<"dev-extend">>, <<"eu">>], <<"dev-extend.eu">>, 8080}},
  133. {<<"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">>,
  134. {[<<"a">>, <<"b">>, <<"c">>, <<"d">>, <<"e">>, <<"f">>, <<"g">>,
  135. <<"h">>, <<"i">>, <<"j">>, <<"k">>, <<"l">>, <<"m">>, <<"n">>,
  136. <<"o">>, <<"p">>, <<"q">>, <<"r">>, <<"s">>, <<"t">>, <<"u">>,
  137. <<"v">>, <<"w">>, <<"x">>, <<"y">>, <<"z">>],
  138. <<"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">>,
  139. undefined}}
  140. ],
  141. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  142. split_host_fail_test_() ->
  143. Tests = [
  144. <<"dev-extend.eu:owns">>,
  145. <<"dev-extend.eu: owns">>,
  146. <<"dev-extend.eu:42fun">>,
  147. <<"dev-extend.eu: 42fun">>,
  148. <<"dev-extend.eu:42 fun">>,
  149. <<"dev-extend.eu:fun 42">>,
  150. <<"dev-extend.eu: 42">>,
  151. <<":owns">>,
  152. <<":42 fun">>
  153. ],
  154. [{H, fun() -> case catch split_host(H) of
  155. {'EXIT', _Reason} -> ok
  156. end end} || H <- Tests].
  157. split_path_test_() ->
  158. %% {Path, Result, QueryString}
  159. Tests = [
  160. {<<"?">>, [], <<"">>, <<"">>},
  161. {<<"???">>, [], <<"">>, <<"??">>},
  162. {<<"/">>, [], <<"/">>, <<"">>},
  163. {<<"/users">>, [<<"users">>], <<"/users">>, <<"">>},
  164. {<<"/users?">>, [<<"users">>], <<"/users">>, <<"">>},
  165. {<<"/users?a">>, [<<"users">>], <<"/users">>, <<"a">>},
  166. {<<"/users/42/friends?a=b&c=d&e=notsure?whatever">>,
  167. [<<"users">>, <<"42">>, <<"friends">>],
  168. <<"/users/42/friends">>, <<"a=b&c=d&e=notsure?whatever">>}
  169. ],
  170. [{P, fun() -> {R, RawP, Qs} = split_path(P) end}
  171. || {P, R, RawP, Qs} <- Tests].
  172. match_test_() ->
  173. Dispatch = [
  174. {[<<"www">>, '_', <<"dev-extend">>, <<"eu">>], [
  175. {[<<"users">>, '_', <<"mails">>], match_any_subdomain_users, []}
  176. ]},
  177. {[<<"dev-extend">>, <<"eu">>], [
  178. {[<<"users">>, id, <<"friends">>], match_extend_users_friends, []},
  179. {'_', match_extend, []}
  180. ]},
  181. {[<<"dev-extend">>, var], [
  182. {[<<"threads">>, var], match_duplicate_vars,
  183. [we, {expect, two}, var, here]}
  184. ]},
  185. {[<<"erlang">>, ext], [
  186. {'_', match_erlang_ext, []}
  187. ]},
  188. {'_', [
  189. {[<<"users">>, id, <<"friends">>], match_users_friends, []},
  190. {'_', match_any, []}
  191. ]}
  192. ],
  193. %% {Host, Path, Result}
  194. Tests = [
  195. {[<<"any">>], [], {ok, match_any, [], []}},
  196. {[<<"www">>, <<"any">>, <<"dev-extend">>, <<"eu">>],
  197. [<<"users">>, <<"42">>, <<"mails">>],
  198. {ok, match_any_subdomain_users, [], []}},
  199. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  200. [<<"users">>, <<"42">>, <<"mails">>], {ok, match_any, [], []}},
  201. {[<<"www">>, <<"dev-extend">>, <<"eu">>], [], {ok, match_any, [], []}},
  202. {[<<"www">>, <<"any">>, <<"dev-extend">>, <<"eu">>],
  203. [<<"not_users">>, <<"42">>, <<"mails">>], {error, notfound, path}},
  204. {[<<"dev-extend">>, <<"eu">>], [], {ok, match_extend, [], []}},
  205. {[<<"dev-extend">>, <<"eu">>], [<<"users">>, <<"42">>, <<"friends">>],
  206. {ok, match_extend_users_friends, [], [{id, <<"42">>}]}},
  207. {[<<"erlang">>, <<"fr">>], '_',
  208. {ok, match_erlang_ext, [], [{ext, <<"fr">>}]}},
  209. {[<<"any">>], [<<"users">>, <<"444">>, <<"friends">>],
  210. {ok, match_users_friends, [], [{id, <<"444">>}]}},
  211. {[<<"dev-extend">>, <<"fr">>], [<<"threads">>, <<"987">>],
  212. {ok, match_duplicate_vars, [we, {expect, two}, var, here],
  213. [{var, <<"fr">>}, {var, <<"987">>}]}}
  214. ],
  215. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  216. {ok, Handler, Opts, Binds, undefined, undefined} = match(H, P, Dispatch)
  217. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  218. match_info_test_() ->
  219. Dispatch = [
  220. {[<<"www">>, <<"dev-extend">>, <<"eu">>], [
  221. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], match_path, []}
  222. ]},
  223. {['...', <<"dev-extend">>, <<"eu">>], [
  224. {'_', match_any, []}
  225. ]}
  226. ],
  227. Tests = [
  228. {[<<"dev-extend">>, <<"eu">>], [],
  229. {ok, match_any, [], [], [], undefined}},
  230. {[<<"bugs">>, <<"dev-extend">>, <<"eu">>], [],
  231. {ok, match_any, [], [], [<<"bugs">>], undefined}},
  232. {[<<"cowboy">>, <<"bugs">>, <<"dev-extend">>, <<"eu">>], [],
  233. {ok, match_any, [], [], [<<"cowboy">>, <<"bugs">>], undefined}},
  234. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  235. [<<"pathinfo">>, <<"is">>, <<"next">>],
  236. {ok, match_path, [], [], undefined, []}},
  237. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  238. [<<"pathinfo">>, <<"is">>, <<"next">>, <<"path_info">>],
  239. {ok, match_path, [], [], undefined, [<<"path_info">>]}},
  240. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  241. [<<"pathinfo">>, <<"is">>, <<"next">>, <<"foo">>, <<"bar">>],
  242. {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}}
  243. ],
  244. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  245. R = match(H, P, Dispatch)
  246. end} || {H, P, R} <- Tests].
  247. -endif.