cowboy_router.erl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. %% Copyright (c) 2011-2013, Loïc Hoguin <essen@ninenines.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. %% @doc Routing middleware.
  15. %%
  16. %% Resolve the handler to be used for the request based on the
  17. %% routing information found in the <em>dispatch</em> environment value.
  18. %% When found, the handler module and associated data are added to
  19. %% the environment as the <em>handler</em> and <em>handler_opts</em> values
  20. %% respectively.
  21. %%
  22. %% If the route cannot be found, processing stops with either
  23. %% a 400 or a 404 reply.
  24. -module(cowboy_router).
  25. -behaviour(cowboy_middleware).
  26. -export([compile/1]).
  27. -export([execute/2]).
  28. -type bindings() :: [{atom(), binary()}].
  29. -type tokens() :: [binary()].
  30. -export_type([bindings/0]).
  31. -export_type([tokens/0]).
  32. -type constraints() :: [{atom(), int}
  33. | {atom(), function, fun ((binary()) -> true | {true, any()} | false)}].
  34. -export_type([constraints/0]).
  35. -type route_match() :: '_' | binary() | string().
  36. -type route_path() :: {Path::route_match(), Handler::module(), Opts::any()}
  37. | {Path::route_match(), constraints(), Handler::module(), Opts::any()}.
  38. -type route_rule() :: {Host::route_match(), Paths::[route_path()]}
  39. | {Host::route_match(), constraints(), Paths::[route_path()]}.
  40. -type routes() :: [route_rule()].
  41. -export_type([routes/0]).
  42. -type dispatch_match() :: '_' | <<_:8>> | [binary() | '_' | '...' | atom()].
  43. -type dispatch_path() :: {dispatch_match(), module(), any()}.
  44. -type dispatch_rule() :: {Host::dispatch_match(), Paths::[dispatch_path()]}.
  45. -opaque dispatch_rules() :: [dispatch_rule()].
  46. -export_type([dispatch_rules/0]).
  47. -ifdef(TEST).
  48. -include_lib("eunit/include/eunit.hrl").
  49. -endif.
  50. %% @doc Compile a list of routes into the dispatch format used
  51. %% by Cowboy's routing.
  52. -spec compile(routes()) -> dispatch_rules().
  53. compile(Routes) ->
  54. compile(Routes, []).
  55. compile([], Acc) ->
  56. lists:reverse(Acc);
  57. compile([{Host, Paths}|Tail], Acc) ->
  58. compile([{Host, [], Paths}|Tail], Acc);
  59. compile([{HostMatch, Constraints, Paths}|Tail], Acc) ->
  60. HostRules = case HostMatch of
  61. '_' -> '_';
  62. _ -> compile_host(HostMatch)
  63. end,
  64. PathRules = compile_paths(Paths, []),
  65. Hosts = case HostRules of
  66. '_' -> [{'_', Constraints, PathRules}];
  67. _ -> [{R, Constraints, PathRules} || R <- HostRules]
  68. end,
  69. compile(Tail, Hosts ++ Acc).
  70. compile_host(HostMatch) when is_list(HostMatch) ->
  71. compile_host(list_to_binary(HostMatch));
  72. compile_host(HostMatch) when is_binary(HostMatch) ->
  73. compile_rules(HostMatch, $., [], [], <<>>).
  74. compile_paths([], Acc) ->
  75. lists:reverse(Acc);
  76. compile_paths([{PathMatch, Handler, Opts}|Tail], Acc) ->
  77. compile_paths([{PathMatch, [], Handler, Opts}|Tail], Acc);
  78. compile_paths([{PathMatch, Constraints, Handler, Opts}|Tail], Acc)
  79. when is_list(PathMatch) ->
  80. compile_paths([{list_to_binary(PathMatch),
  81. Constraints, Handler, Opts}|Tail], Acc);
  82. compile_paths([{'_', Constraints, Handler, Opts}|Tail], Acc) ->
  83. compile_paths(Tail, [{'_', Constraints, Handler, Opts}] ++ Acc);
  84. compile_paths([{<< $/, PathMatch/binary >>, Constraints, Handler, Opts}|Tail],
  85. Acc) ->
  86. PathRules = compile_rules(PathMatch, $/, [], [], <<>>),
  87. Paths = [{lists:reverse(R), Constraints, Handler, Opts} || R <- PathRules],
  88. compile_paths(Tail, Paths ++ Acc).
  89. compile_rules(<<>>, _, Segments, Rules, <<>>) ->
  90. [Segments|Rules];
  91. compile_rules(<<>>, _, Segments, Rules, Acc) ->
  92. [[Acc|Segments]|Rules];
  93. compile_rules(<< S, Rest/binary >>, S, Segments, Rules, <<>>) ->
  94. compile_rules(Rest, S, Segments, Rules, <<>>);
  95. compile_rules(<< S, Rest/binary >>, S, Segments, Rules, Acc) ->
  96. compile_rules(Rest, S, [Acc|Segments], Rules, <<>>);
  97. compile_rules(<< $:, Rest/binary >>, S, Segments, Rules, <<>>) ->
  98. {NameBin, Rest2} = compile_binding(Rest, S, <<>>),
  99. Name = binary_to_atom(NameBin, utf8),
  100. compile_rules(Rest2, S, Segments, Rules, Name);
  101. compile_rules(<< $:, _/binary >>, _, _, _, _) ->
  102. erlang:error(badarg);
  103. compile_rules(<< $[, $., $., $., $], Rest/binary >>, S, Segments, Rules, Acc)
  104. when Acc =:= <<>> ->
  105. compile_rules(Rest, S, ['...'|Segments], Rules, Acc);
  106. compile_rules(<< $[, $., $., $., $], Rest/binary >>, S, Segments, Rules, Acc) ->
  107. compile_rules(Rest, S, ['...', Acc|Segments], Rules, Acc);
  108. compile_rules(<< $[, S, Rest/binary >>, S, Segments, Rules, Acc) ->
  109. compile_brackets(Rest, S, [Acc|Segments], Rules);
  110. compile_rules(<< $[, Rest/binary >>, S, Segments, Rules, <<>>) ->
  111. compile_brackets(Rest, S, Segments, Rules);
  112. %% Open bracket in the middle of a segment.
  113. compile_rules(<< $[, _/binary >>, _, _, _, _) ->
  114. erlang:error(badarg);
  115. %% Missing an open bracket.
  116. compile_rules(<< $], _/binary >>, _, _, _, _) ->
  117. erlang:error(badarg);
  118. compile_rules(<< C, Rest/binary >>, S, Segments, Rules, Acc) ->
  119. compile_rules(Rest, S, Segments, Rules, << Acc/binary, C >>).
  120. %% Everything past $: until the segment separator ($. for hosts,
  121. %% $/ for paths) or $[ or $] or end of binary is the binding name.
  122. compile_binding(<<>>, _, <<>>) ->
  123. erlang:error(badarg);
  124. compile_binding(Rest = <<>>, _, Acc) ->
  125. {Acc, Rest};
  126. compile_binding(Rest = << C, _/binary >>, S, Acc)
  127. when C =:= S; C =:= $[; C =:= $] ->
  128. {Acc, Rest};
  129. compile_binding(<< C, Rest/binary >>, S, Acc) ->
  130. compile_binding(Rest, S, << Acc/binary, C >>).
  131. compile_brackets(Rest, S, Segments, Rules) ->
  132. {Bracket, Rest2} = compile_brackets_split(Rest, <<>>, 0),
  133. Rules1 = compile_rules(Rest2, S, Segments, [], <<>>),
  134. Rules2 = compile_rules(<< Bracket/binary, Rest2/binary >>,
  135. S, Segments, [], <<>>),
  136. Rules ++ Rules2 ++ Rules1.
  137. %% Missing a close bracket.
  138. compile_brackets_split(<<>>, _, _) ->
  139. erlang:error(badarg);
  140. %% Make sure we don't confuse the closing bracket we're looking for.
  141. compile_brackets_split(<< C, Rest/binary >>, Acc, N) when C =:= $[ ->
  142. compile_brackets_split(Rest, << Acc/binary, C >>, N + 1);
  143. compile_brackets_split(<< C, Rest/binary >>, Acc, N) when C =:= $], N > 0 ->
  144. compile_brackets_split(Rest, << Acc/binary, C >>, N - 1);
  145. %% That's the right one.
  146. compile_brackets_split(<< $], Rest/binary >>, Acc, 0) ->
  147. {Acc, Rest};
  148. compile_brackets_split(<< C, Rest/binary >>, Acc, N) ->
  149. compile_brackets_split(Rest, << Acc/binary, C >>, N).
  150. %% @private
  151. -spec execute(Req, Env)
  152. -> {ok, Req, Env} | {error, 400 | 404, Req}
  153. when Req::cowboy_req:req(), Env::cowboy_middleware:env().
  154. execute(Req, Env) ->
  155. {_, Dispatch} = lists:keyfind(dispatch, 1, Env),
  156. [Host, Path] = cowboy_req:get([host, path], Req),
  157. case match(Dispatch, Host, Path) of
  158. {ok, Handler, HandlerOpts, Bindings, HostInfo, PathInfo} ->
  159. Req2 = cowboy_req:set_bindings(HostInfo, PathInfo, Bindings, Req),
  160. {ok, Req2, [{handler, Handler}, {handler_opts, HandlerOpts}|Env]};
  161. {error, notfound, host} ->
  162. {error, 400, Req};
  163. {error, badrequest, path} ->
  164. {error, 400, Req};
  165. {error, notfound, path} ->
  166. {error, 404, Req}
  167. end.
  168. %% Internal.
  169. %% @doc Match hostname tokens and path tokens against dispatch rules.
  170. %%
  171. %% It is typically used for matching tokens for the hostname and path of
  172. %% the request against a global dispatch rule for your listener.
  173. %%
  174. %% Dispatch rules are a list of <em>{Hostname, PathRules}</em> tuples, with
  175. %% <em>PathRules</em> being a list of <em>{Path, HandlerMod, HandlerOpts}</em>.
  176. %%
  177. %% <em>Hostname</em> and <em>Path</em> are match rules and can be either the
  178. %% atom <em>'_'</em>, which matches everything, `<<"*">>', which match the
  179. %% wildcard path, or a list of tokens.
  180. %%
  181. %% Each token can be either a binary, the atom <em>'_'</em>,
  182. %% the atom '...' or a named atom. A binary token must match exactly,
  183. %% <em>'_'</em> matches everything for a single token, <em>'...'</em> matches
  184. %% everything for the rest of the tokens and a named atom will bind the
  185. %% corresponding token value and return it.
  186. %%
  187. %% The list of hostname tokens is reversed before matching. For example, if
  188. %% we were to match "www.ninenines.eu", we would first match "eu", then
  189. %% "ninenines", then "www". This means that in the context of hostnames,
  190. %% the <em>'...'</em> atom matches properly the lower levels of the domain
  191. %% as would be expected.
  192. %%
  193. %% When a result is found, this function will return the handler module and
  194. %% options found in the dispatch list, a key-value list of bindings and
  195. %% the tokens that were matched by the <em>'...'</em> atom for both the
  196. %% hostname and path.
  197. -spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary())
  198. -> {ok, module(), any(), bindings(),
  199. HostInfo::undefined | tokens(),
  200. PathInfo::undefined | tokens()}
  201. | {error, notfound, host} | {error, notfound, path}
  202. | {error, badrequest, path}.
  203. match([], _, _) ->
  204. {error, notfound, host};
  205. %% If the host is '_' then there can be no constraints.
  206. match([{'_', [], PathMatchs}|_Tail], _, Path) ->
  207. match_path(PathMatchs, undefined, Path, []);
  208. match([{HostMatch, Constraints, PathMatchs}|Tail], Tokens, Path)
  209. when is_list(Tokens) ->
  210. case list_match(Tokens, HostMatch, []) of
  211. false ->
  212. match(Tail, Tokens, Path);
  213. {true, Bindings, HostInfo} ->
  214. HostInfo2 = case HostInfo of
  215. undefined -> undefined;
  216. _ -> lists:reverse(HostInfo)
  217. end,
  218. case check_constraints(Constraints, Bindings) of
  219. {ok, Bindings2} ->
  220. match_path(PathMatchs, HostInfo2, Path, Bindings2);
  221. nomatch ->
  222. match(Tail, Tokens, Path)
  223. end
  224. end;
  225. match(Dispatch, Host, Path) ->
  226. match(Dispatch, split_host(Host), Path).
  227. -spec match_path([dispatch_path()],
  228. HostInfo::undefined | tokens(), binary() | tokens(), bindings())
  229. -> {ok, module(), any(), bindings(),
  230. HostInfo::undefined | tokens(),
  231. PathInfo::undefined | tokens()}
  232. | {error, notfound, path} | {error, badrequest, path}.
  233. match_path([], _, _, _) ->
  234. {error, notfound, path};
  235. %% If the path is '_' then there can be no constraints.
  236. match_path([{'_', [], Handler, Opts}|_Tail], HostInfo, _, Bindings) ->
  237. {ok, Handler, Opts, Bindings, HostInfo, undefined};
  238. match_path([{<<"*">>, _Constraints, Handler, Opts}|_Tail], HostInfo, <<"*">>, Bindings) ->
  239. {ok, Handler, Opts, Bindings, HostInfo, undefined};
  240. match_path([{PathMatch, Constraints, Handler, Opts}|Tail], HostInfo, Tokens,
  241. Bindings) when is_list(Tokens) ->
  242. case list_match(Tokens, PathMatch, Bindings) of
  243. false ->
  244. match_path(Tail, HostInfo, Tokens, Bindings);
  245. {true, PathBinds, PathInfo} ->
  246. case check_constraints(Constraints, PathBinds) of
  247. {ok, PathBinds2} ->
  248. {ok, Handler, Opts, PathBinds2, HostInfo, PathInfo};
  249. nomatch ->
  250. match_path(Tail, HostInfo, Tokens, Bindings)
  251. end
  252. end;
  253. match_path(_Dispatch, _HostInfo, badrequest, _Bindings) ->
  254. {error, badrequest, path};
  255. match_path(Dispatch, HostInfo, Path, Bindings) ->
  256. match_path(Dispatch, HostInfo, split_path(Path), Bindings).
  257. check_constraints([], Bindings) ->
  258. {ok, Bindings};
  259. check_constraints([Constraint|Tail], Bindings) ->
  260. Name = element(1, Constraint),
  261. case lists:keyfind(Name, 1, Bindings) of
  262. false ->
  263. check_constraints(Tail, Bindings);
  264. {_, Value} ->
  265. case check_constraint(Constraint, Value) of
  266. true ->
  267. check_constraints(Tail, Bindings);
  268. {true, Value2} ->
  269. Bindings2 = lists:keyreplace(Name, 1, Bindings,
  270. {Name, Value2}),
  271. check_constraints(Tail, Bindings2);
  272. false ->
  273. nomatch
  274. end
  275. end.
  276. check_constraint({_, int}, Value) ->
  277. try {true, list_to_integer(binary_to_list(Value))}
  278. catch _:_ -> false
  279. end;
  280. check_constraint({_, function, Fun}, Value) ->
  281. Fun(Value).
  282. %% @doc Split a hostname into a list of tokens.
  283. -spec split_host(binary()) -> tokens().
  284. split_host(Host) ->
  285. split_host(Host, []).
  286. split_host(Host, Acc) ->
  287. case binary:match(Host, <<".">>) of
  288. nomatch when Host =:= <<>> ->
  289. Acc;
  290. nomatch ->
  291. [Host|Acc];
  292. {Pos, _} ->
  293. << Segment:Pos/binary, _:8, Rest/bits >> = Host,
  294. false = byte_size(Segment) == 0,
  295. split_host(Rest, [Segment|Acc])
  296. end.
  297. %% @doc Split a path into a list of path segments.
  298. %%
  299. %% Following RFC2396, this function may return path segments containing any
  300. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  301. %% and part of a path segment.
  302. -spec split_path(binary()) -> tokens().
  303. split_path(<< $/, Path/bits >>) ->
  304. split_path(Path, []);
  305. split_path(_) ->
  306. badrequest.
  307. split_path(Path, Acc) ->
  308. try
  309. case binary:match(Path, <<"/">>) of
  310. nomatch when Path =:= <<>> ->
  311. lists:reverse([cowboy_http:urldecode(S) || S <- Acc]);
  312. nomatch ->
  313. lists:reverse([cowboy_http:urldecode(S) || S <- [Path|Acc]]);
  314. {Pos, _} ->
  315. << Segment:Pos/binary, _:8, Rest/bits >> = Path,
  316. split_path(Rest, [Segment|Acc])
  317. end
  318. catch
  319. error:badarg ->
  320. badrequest
  321. end.
  322. -spec list_match(tokens(), dispatch_match(), bindings())
  323. -> {true, bindings(), undefined | tokens()} | false.
  324. %% Atom '...' matches any trailing path, stop right now.
  325. list_match(List, ['...'], Binds) ->
  326. {true, Binds, List};
  327. %% Atom '_' matches anything, continue.
  328. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  329. list_match(Tail, TailMatch, Binds);
  330. %% Both values match, continue.
  331. list_match([E|Tail], [E|TailMatch], Binds) ->
  332. list_match(Tail, TailMatch, Binds);
  333. %% Bind E to the variable name V and continue,
  334. %% unless V was already defined and E isn't identical to the previous value.
  335. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  336. case lists:keyfind(V, 1, Binds) of
  337. {_, E} ->
  338. list_match(Tail, TailMatch, Binds);
  339. {_, _} ->
  340. false;
  341. false ->
  342. list_match(Tail, TailMatch, [{V, E}|Binds])
  343. end;
  344. %% Match complete.
  345. list_match([], [], Binds) ->
  346. {true, Binds, undefined};
  347. %% Values don't match, stop.
  348. list_match(_List, _Match, _Binds) ->
  349. false.
  350. %% Tests.
  351. -ifdef(TEST).
  352. compile_test_() ->
  353. %% {Routes, Result}
  354. Tests = [
  355. %% Match any host and path.
  356. {[{'_', [{'_', h, o}]}],
  357. [{'_', [], [{'_', [], h, o}]}]},
  358. {[{"cowboy.example.org",
  359. [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}],
  360. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [
  361. {[], [], ha, oa},
  362. {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]},
  363. {[{'_', [{"/path/to/resource/", h, o}]}],
  364. [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]},
  365. {[{'_', [{"/путь/к/ресурсу/", h, o}]}],
  366. [{'_', [], [{[<<"путь">>, <<"к">>, <<"ресурсу">>], [], h, o}]}]},
  367. {[{"cowboy.example.org.", [{'_', h, o}]}],
  368. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]},
  369. {[{".cowboy.example.org", [{'_', h, o}]}],
  370. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]},
  371. {[{"некий.сайт.рф.", [{'_', h, o}]}],
  372. [{[<<"рф">>, <<"сайт">>, <<"некий">>], [], [{'_', [], h, o}]}]},
  373. {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}],
  374. [{[<<"org">>, <<"example">>, subdomain], [], [
  375. {[<<"hats">>, name, <<"prices">>], [], h, o}]}]},
  376. {[{"ninenines.:_", [{"/hats/:_", h, o}]}],
  377. [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]},
  378. {[{"[www.]ninenines.eu",
  379. [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [
  380. {[<<"eu">>, <<"ninenines">>], [], [
  381. {[<<"horses">>], [], h, o},
  382. {[<<"hats">>], [], h, o},
  383. {[<<"hats">>, <<"page">>, number], [], h, o}]},
  384. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  385. {[<<"horses">>], [], h, o},
  386. {[<<"hats">>], [], h, o},
  387. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  388. {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [
  389. {[<<"hats">>], [], h, o},
  390. {[<<"hats">>, <<"page">>], [], h, o},
  391. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  392. {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}],
  393. [{[<<"eu">>, <<"ninenines">>, '...'], [], [
  394. {[<<"hats">>, '...'], [], h, o}]}]}
  395. ],
  396. [{lists:flatten(io_lib:format("~p", [Rt])),
  397. fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests].
  398. split_host_test_() ->
  399. %% {Host, Result}
  400. Tests = [
  401. {<<"">>, []},
  402. {<<"*">>, [<<"*">>]},
  403. {<<"cowboy.ninenines.eu">>,
  404. [<<"eu">>, <<"ninenines">>, <<"cowboy">>]},
  405. {<<"ninenines.eu">>,
  406. [<<"eu">>, <<"ninenines">>]},
  407. {<<"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">>,
  408. [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>,
  409. <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>,
  410. <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>,
  411. <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]}
  412. ],
  413. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  414. split_path_test_() ->
  415. %% {Path, Result, QueryString}
  416. Tests = [
  417. {<<"/">>, []},
  418. {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]},
  419. {<<"/users">>, [<<"users">>]},
  420. {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]},
  421. {<<"/users/a+b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]}
  422. ],
  423. [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests].
  424. match_test_() ->
  425. Dispatch = [
  426. {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [
  427. {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []}
  428. ]},
  429. {[<<"eu">>, <<"ninenines">>], [], [
  430. {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []},
  431. {'_', [], match_extend, []}
  432. ]},
  433. {[var, <<"ninenines">>], [], [
  434. {[<<"threads">>, var], [], match_duplicate_vars,
  435. [we, {expect, two}, var, here]}
  436. ]},
  437. {[ext, <<"erlang">>], [], [
  438. {'_', [], match_erlang_ext, []}
  439. ]},
  440. {'_', [], [
  441. {[<<"users">>, id, <<"friends">>], [], match_users_friends, []},
  442. {'_', [], match_any, []}
  443. ]}
  444. ],
  445. %% {Host, Path, Result}
  446. Tests = [
  447. {<<"any">>, <<"/">>, {ok, match_any, [], []}},
  448. {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>,
  449. {ok, match_any_subdomain_users, [], []}},
  450. {<<"www.ninenines.eu">>, <<"/users/42/mails">>,
  451. {ok, match_any, [], []}},
  452. {<<"www.ninenines.eu">>, <<"/">>,
  453. {ok, match_any, [], []}},
  454. {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>,
  455. {error, notfound, path}},
  456. {<<"ninenines.eu">>, <<"/">>,
  457. {ok, match_extend, [], []}},
  458. {<<"ninenines.eu">>, <<"/users/42/friends">>,
  459. {ok, match_extend_users_friends, [], [{id, <<"42">>}]}},
  460. {<<"erlang.fr">>, '_',
  461. {ok, match_erlang_ext, [], [{ext, <<"fr">>}]}},
  462. {<<"any">>, <<"/users/444/friends">>,
  463. {ok, match_users_friends, [], [{id, <<"444">>}]}}
  464. ],
  465. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  466. {ok, Handler, Opts, Binds, undefined, undefined}
  467. = match(Dispatch, H, P)
  468. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  469. match_info_test_() ->
  470. Dispatch = [
  471. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  472. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []}
  473. ]},
  474. {[<<"eu">>, <<"ninenines">>, '...'], [], [
  475. {'_', [], match_any, []}
  476. ]},
  477. {[<<"рф">>, <<"сайт">>], [], [
  478. {[<<"путь">>, '...'], [], match_path, []}
  479. ]}
  480. ],
  481. Tests = [
  482. {<<"ninenines.eu">>, <<"/">>,
  483. {ok, match_any, [], [], [], undefined}},
  484. {<<"bugs.ninenines.eu">>, <<"/">>,
  485. {ok, match_any, [], [], [<<"bugs">>], undefined}},
  486. {<<"cowboy.bugs.ninenines.eu">>, <<"/">>,
  487. {ok, match_any, [], [], [<<"cowboy">>, <<"bugs">>], undefined}},
  488. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>,
  489. {ok, match_path, [], [], undefined, []}},
  490. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>,
  491. {ok, match_path, [], [], undefined, [<<"path_info">>]}},
  492. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>,
  493. {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}},
  494. {<<"сайт.рф">>, <<"/путь/домой">>,
  495. {ok, match_path, [], [], undefined, [<<"домой">>]}}
  496. ],
  497. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  498. R = match(Dispatch, H, P)
  499. end} || {H, P, R} <- Tests].
  500. match_constraints_test() ->
  501. Dispatch = [{'_', [],
  502. [{[<<"path">>, value], [{value, int}], match, []}]}],
  503. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  504. <<"ninenines.eu">>, <<"/path/123">>),
  505. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  506. <<"ninenines.eu">>, <<"/path/123/">>),
  507. {error, notfound, path} = match(Dispatch,
  508. <<"ninenines.eu">>, <<"/path/NaN/">>),
  509. Dispatch2 = [{'_', [],
  510. [{[<<"path">>, username], [{username, function,
  511. fun(Value) -> Value =:= cowboy_bstr:to_lower(Value) end}],
  512. match, []}]}],
  513. {ok, _, [], [{username, <<"essen">>}], _, _} = match(Dispatch2,
  514. <<"ninenines.eu">>, <<"/path/essen">>),
  515. {error, notfound, path} = match(Dispatch2,
  516. <<"ninenines.eu">>, <<"/path/ESSEN">>),
  517. ok.
  518. match_same_bindings_test() ->
  519. Dispatch = [{[same, same], [], [{'_', [], match, []}]}],
  520. {ok, _, [], [{same, <<"eu">>}], _, _} = match(Dispatch,
  521. <<"eu.eu">>, <<"/">>),
  522. {error, notfound, host} = match(Dispatch,
  523. <<"ninenines.eu">>, <<"/">>),
  524. Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [],
  525. [{[<<"path">>, user], [], match, []}]}],
  526. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  527. <<"essen.ninenines.eu">>, <<"/path/essen">>),
  528. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  529. <<"essen.ninenines.eu">>, <<"/path/essen/">>),
  530. {error, notfound, path} = match(Dispatch2,
  531. <<"essen.ninenines.eu">>, <<"/path/notessen">>),
  532. Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}],
  533. {ok, _, [], [{same, <<"path">>}], _, _} = match(Dispatch3,
  534. <<"ninenines.eu">>, <<"/path/path">>),
  535. {error, notfound, path} = match(Dispatch3,
  536. <<"ninenines.eu">>, <<"/path/to">>),
  537. ok.
  538. -endif.