cowboy_router.erl 21 KB

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