cowboy_router.erl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. %% Copyright (c) 2011-2014, 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. %% 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. -spec compile(routes()) -> dispatch_rules().
  48. compile(Routes) ->
  49. compile(Routes, []).
  50. compile([], Acc) ->
  51. lists:reverse(Acc);
  52. compile([{Host, Paths}|Tail], Acc) ->
  53. compile([{Host, [], Paths}|Tail], Acc);
  54. compile([{HostMatch, Constraints, Paths}|Tail], Acc) ->
  55. HostRules = case HostMatch of
  56. '_' -> '_';
  57. _ -> compile_host(HostMatch)
  58. end,
  59. PathRules = compile_paths(Paths, []),
  60. Hosts = case HostRules of
  61. '_' -> [{'_', Constraints, PathRules}];
  62. _ -> [{R, Constraints, PathRules} || R <- HostRules]
  63. end,
  64. compile(Tail, Hosts ++ Acc).
  65. compile_host(HostMatch) when is_list(HostMatch) ->
  66. compile_host(list_to_binary(HostMatch));
  67. compile_host(HostMatch) when is_binary(HostMatch) ->
  68. compile_rules(HostMatch, $., [], [], <<>>).
  69. compile_paths([], Acc) ->
  70. lists:reverse(Acc);
  71. compile_paths([{PathMatch, Handler, Opts}|Tail], Acc) ->
  72. compile_paths([{PathMatch, [], Handler, Opts}|Tail], Acc);
  73. compile_paths([{PathMatch, Constraints, Handler, Opts}|Tail], Acc)
  74. when is_list(PathMatch) ->
  75. compile_paths([{iolist_to_binary(PathMatch),
  76. Constraints, Handler, Opts}|Tail], Acc);
  77. compile_paths([{'_', Constraints, Handler, Opts}|Tail], Acc) ->
  78. compile_paths(Tail, [{'_', Constraints, Handler, Opts}] ++ Acc);
  79. compile_paths([{<< $/, PathMatch/binary >>, Constraints, Handler, Opts}|Tail],
  80. Acc) ->
  81. PathRules = compile_rules(PathMatch, $/, [], [], <<>>),
  82. Paths = [{lists:reverse(R), Constraints, Handler, Opts} || R <- PathRules],
  83. compile_paths(Tail, Paths ++ Acc);
  84. compile_paths([{PathMatch, _, _, _}|_], _) ->
  85. error({badarg, "The following route MUST begin with a slash: "
  86. ++ binary_to_list(PathMatch)}).
  87. compile_rules(<<>>, _, Segments, Rules, <<>>) ->
  88. [Segments|Rules];
  89. compile_rules(<<>>, _, Segments, Rules, Acc) ->
  90. [[Acc|Segments]|Rules];
  91. compile_rules(<< S, Rest/binary >>, S, Segments, Rules, <<>>) ->
  92. compile_rules(Rest, S, Segments, Rules, <<>>);
  93. compile_rules(<< S, Rest/binary >>, S, Segments, Rules, Acc) ->
  94. compile_rules(Rest, S, [Acc|Segments], Rules, <<>>);
  95. compile_rules(<< $:, Rest/binary >>, S, Segments, Rules, <<>>) ->
  96. {NameBin, Rest2} = compile_binding(Rest, S, <<>>),
  97. Name = binary_to_atom(NameBin, utf8),
  98. compile_rules(Rest2, S, Segments, Rules, Name);
  99. compile_rules(<< $:, _/binary >>, _, _, _, _) ->
  100. erlang:error(badarg);
  101. compile_rules(<< $[, $., $., $., $], Rest/binary >>, S, Segments, Rules, Acc)
  102. when Acc =:= <<>> ->
  103. compile_rules(Rest, S, ['...'|Segments], Rules, Acc);
  104. compile_rules(<< $[, $., $., $., $], Rest/binary >>, S, Segments, Rules, Acc) ->
  105. compile_rules(Rest, S, ['...', Acc|Segments], Rules, Acc);
  106. compile_rules(<< $[, S, Rest/binary >>, S, Segments, Rules, Acc) ->
  107. compile_brackets(Rest, S, [Acc|Segments], Rules);
  108. compile_rules(<< $[, Rest/binary >>, S, Segments, Rules, <<>>) ->
  109. compile_brackets(Rest, S, Segments, Rules);
  110. %% Open bracket in the middle of a segment.
  111. compile_rules(<< $[, _/binary >>, _, _, _, _) ->
  112. erlang:error(badarg);
  113. %% Missing an open bracket.
  114. compile_rules(<< $], _/binary >>, _, _, _, _) ->
  115. erlang:error(badarg);
  116. compile_rules(<< C, Rest/binary >>, S, Segments, Rules, Acc) ->
  117. compile_rules(Rest, S, Segments, Rules, << Acc/binary, C >>).
  118. %% Everything past $: until the segment separator ($. for hosts,
  119. %% $/ for paths) or $[ or $] or end of binary is the binding name.
  120. compile_binding(<<>>, _, <<>>) ->
  121. erlang:error(badarg);
  122. compile_binding(Rest = <<>>, _, Acc) ->
  123. {Acc, Rest};
  124. compile_binding(Rest = << C, _/binary >>, S, Acc)
  125. when C =:= S; C =:= $[; C =:= $] ->
  126. {Acc, Rest};
  127. compile_binding(<< C, Rest/binary >>, S, Acc) ->
  128. compile_binding(Rest, S, << Acc/binary, C >>).
  129. compile_brackets(Rest, S, Segments, Rules) ->
  130. {Bracket, Rest2} = compile_brackets_split(Rest, <<>>, 0),
  131. Rules1 = compile_rules(Rest2, S, Segments, [], <<>>),
  132. Rules2 = compile_rules(<< Bracket/binary, Rest2/binary >>,
  133. S, Segments, [], <<>>),
  134. Rules ++ Rules2 ++ Rules1.
  135. %% Missing a close bracket.
  136. compile_brackets_split(<<>>, _, _) ->
  137. erlang:error(badarg);
  138. %% Make sure we don't confuse the closing bracket we're looking for.
  139. compile_brackets_split(<< C, Rest/binary >>, Acc, N) when C =:= $[ ->
  140. compile_brackets_split(Rest, << Acc/binary, C >>, N + 1);
  141. compile_brackets_split(<< C, Rest/binary >>, Acc, N) when C =:= $], N > 0 ->
  142. compile_brackets_split(Rest, << Acc/binary, C >>, N - 1);
  143. %% That's the right one.
  144. compile_brackets_split(<< $], Rest/binary >>, Acc, 0) ->
  145. {Acc, Rest};
  146. compile_brackets_split(<< C, Rest/binary >>, Acc, N) ->
  147. compile_brackets_split(Rest, << Acc/binary, C >>, N).
  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. %% 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. -spec split_host(binary()) -> tokens().
  280. split_host(Host) ->
  281. split_host(Host, []).
  282. split_host(Host, Acc) ->
  283. case binary:match(Host, <<".">>) of
  284. nomatch when Host =:= <<>> ->
  285. Acc;
  286. nomatch ->
  287. [Host|Acc];
  288. {Pos, _} ->
  289. << Segment:Pos/binary, _:8, Rest/bits >> = Host,
  290. false = byte_size(Segment) == 0,
  291. split_host(Rest, [Segment|Acc])
  292. end.
  293. %% Following RFC2396, this function may return path segments containing any
  294. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  295. %% and part of a path segment.
  296. -spec split_path(binary()) -> tokens().
  297. split_path(<< $/, Path/bits >>) ->
  298. split_path(Path, []);
  299. split_path(_) ->
  300. badrequest.
  301. split_path(Path, Acc) ->
  302. try
  303. case binary:match(Path, <<"/">>) of
  304. nomatch when Path =:= <<>> ->
  305. lists:reverse([cow_qs:urldecode(S) || S <- Acc]);
  306. nomatch ->
  307. lists:reverse([cow_qs:urldecode(S) || S <- [Path|Acc]]);
  308. {Pos, _} ->
  309. << Segment:Pos/binary, _:8, Rest/bits >> = Path,
  310. split_path(Rest, [Segment|Acc])
  311. end
  312. catch
  313. error:badarg ->
  314. badrequest
  315. end.
  316. -spec list_match(tokens(), dispatch_match(), bindings())
  317. -> {true, bindings(), undefined | tokens()} | false.
  318. %% Atom '...' matches any trailing path, stop right now.
  319. list_match(List, ['...'], Binds) ->
  320. {true, Binds, List};
  321. %% Atom '_' matches anything, continue.
  322. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  323. list_match(Tail, TailMatch, Binds);
  324. %% Both values match, continue.
  325. list_match([E|Tail], [E|TailMatch], Binds) ->
  326. list_match(Tail, TailMatch, Binds);
  327. %% Bind E to the variable name V and continue,
  328. %% unless V was already defined and E isn't identical to the previous value.
  329. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  330. case lists:keyfind(V, 1, Binds) of
  331. {_, E} ->
  332. list_match(Tail, TailMatch, Binds);
  333. {_, _} ->
  334. false;
  335. false ->
  336. list_match(Tail, TailMatch, [{V, E}|Binds])
  337. end;
  338. %% Match complete.
  339. list_match([], [], Binds) ->
  340. {true, Binds, undefined};
  341. %% Values don't match, stop.
  342. list_match(_List, _Match, _Binds) ->
  343. false.
  344. %% Tests.
  345. -ifdef(TEST).
  346. compile_test_() ->
  347. Tests = [
  348. %% Match any host and path.
  349. {[{'_', [{'_', h, o}]}],
  350. [{'_', [], [{'_', [], h, o}]}]},
  351. {[{"cowboy.example.org",
  352. [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}],
  353. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [
  354. {[], [], ha, oa},
  355. {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]},
  356. {[{'_', [{"/path/to/resource/", h, o}]}],
  357. [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]},
  358. % Cyrillic from a latin1 encoded file.
  359. {[{'_', [{[47,208,191,209,131,209,130,209,140,47,208,186,47,209,128,
  360. 208,181,209,129,209,131,209,128,209,129,209,131,47], h, o}]}],
  361. [{'_', [], [{[<<208,191,209,131,209,130,209,140>>, <<208,186>>,
  362. <<209,128,208,181,209,129,209,131,209,128,209,129,209,131>>],
  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. % Cyrillic from a latin1 encoded file.
  369. {[{[208,189,208,181,208,186,208,184,208,185,46,209,129,208,176,
  370. 208,185,209,130,46,209,128,209,132,46], [{'_', h, o}]}],
  371. [{[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>,
  372. <<208,189,208,181,208,186,208,184,208,185>>],
  373. [], [{'_', [], h, o}]}]},
  374. {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}],
  375. [{[<<"org">>, <<"example">>, subdomain], [], [
  376. {[<<"hats">>, name, <<"prices">>], [], h, o}]}]},
  377. {[{"ninenines.:_", [{"/hats/:_", h, o}]}],
  378. [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]},
  379. {[{"[www.]ninenines.eu",
  380. [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [
  381. {[<<"eu">>, <<"ninenines">>], [], [
  382. {[<<"horses">>], [], h, o},
  383. {[<<"hats">>], [], h, o},
  384. {[<<"hats">>, <<"page">>, number], [], h, o}]},
  385. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  386. {[<<"horses">>], [], h, o},
  387. {[<<"hats">>], [], h, o},
  388. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  389. {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [
  390. {[<<"hats">>], [], h, o},
  391. {[<<"hats">>, <<"page">>], [], h, o},
  392. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  393. {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}],
  394. [{[<<"eu">>, <<"ninenines">>, '...'], [], [
  395. {[<<"hats">>, '...'], [], h, o}]}]}
  396. ],
  397. [{lists:flatten(io_lib:format("~p", [Rt])),
  398. fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests].
  399. split_host_test_() ->
  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. Tests = [
  416. {<<"/">>, []},
  417. {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]},
  418. {<<"/users">>, [<<"users">>]},
  419. {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]},
  420. {<<"/users/a+b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]}
  421. ],
  422. [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests].
  423. match_test_() ->
  424. Dispatch = [
  425. {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [
  426. {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []}
  427. ]},
  428. {[<<"eu">>, <<"ninenines">>], [], [
  429. {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []},
  430. {'_', [], match_extend, []}
  431. ]},
  432. {[var, <<"ninenines">>], [], [
  433. {[<<"threads">>, var], [], match_duplicate_vars,
  434. [we, {expect, two}, var, here]}
  435. ]},
  436. {[ext, <<"erlang">>], [], [
  437. {'_', [], match_erlang_ext, []}
  438. ]},
  439. {'_', [], [
  440. {[<<"users">>, id, <<"friends">>], [], match_users_friends, []},
  441. {'_', [], match_any, []}
  442. ]}
  443. ],
  444. Tests = [
  445. {<<"any">>, <<"/">>, {ok, match_any, [], []}},
  446. {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>,
  447. {ok, match_any_subdomain_users, [], []}},
  448. {<<"www.ninenines.eu">>, <<"/users/42/mails">>,
  449. {ok, match_any, [], []}},
  450. {<<"www.ninenines.eu">>, <<"/">>,
  451. {ok, match_any, [], []}},
  452. {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>,
  453. {error, notfound, path}},
  454. {<<"ninenines.eu">>, <<"/">>,
  455. {ok, match_extend, [], []}},
  456. {<<"ninenines.eu">>, <<"/users/42/friends">>,
  457. {ok, match_extend_users_friends, [], [{id, <<"42">>}]}},
  458. {<<"erlang.fr">>, '_',
  459. {ok, match_erlang_ext, [], [{ext, <<"fr">>}]}},
  460. {<<"any">>, <<"/users/444/friends">>,
  461. {ok, match_users_friends, [], [{id, <<"444">>}]}}
  462. ],
  463. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  464. {ok, Handler, Opts, Binds, undefined, undefined}
  465. = match(Dispatch, H, P)
  466. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  467. match_info_test_() ->
  468. Dispatch = [
  469. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  470. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []}
  471. ]},
  472. {[<<"eu">>, <<"ninenines">>, '...'], [], [
  473. {'_', [], match_any, []}
  474. ]},
  475. % Cyrillic from a latin1 encoded file.
  476. {[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>], [], [
  477. {[<<208,191,209,131,209,130,209,140>>, '...'], [], match_path, []}
  478. ]}
  479. ],
  480. Tests = [
  481. {<<"ninenines.eu">>, <<"/">>,
  482. {ok, match_any, [], [], [], undefined}},
  483. {<<"bugs.ninenines.eu">>, <<"/">>,
  484. {ok, match_any, [], [], [<<"bugs">>], undefined}},
  485. {<<"cowboy.bugs.ninenines.eu">>, <<"/">>,
  486. {ok, match_any, [], [], [<<"cowboy">>, <<"bugs">>], undefined}},
  487. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>,
  488. {ok, match_path, [], [], undefined, []}},
  489. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>,
  490. {ok, match_path, [], [], undefined, [<<"path_info">>]}},
  491. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>,
  492. {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}},
  493. % Cyrillic from a latin1 encoded file.
  494. {<<209,129,208,176,208,185,209,130,46,209,128,209,132>>,
  495. <<47,208,191,209,131,209,130,209,140,47,208,180,208,190,208,188,208,190,208,185>>,
  496. {ok, match_path, [], [], undefined, [<<208,180,208,190,208,188,208,190,208,185>>]}}
  497. ],
  498. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  499. R = match(Dispatch, H, P)
  500. end} || {H, P, R} <- Tests].
  501. match_constraints_test() ->
  502. Dispatch = [{'_', [],
  503. [{[<<"path">>, value], [{value, int}], match, []}]}],
  504. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  505. <<"ninenines.eu">>, <<"/path/123">>),
  506. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  507. <<"ninenines.eu">>, <<"/path/123/">>),
  508. {error, notfound, path} = match(Dispatch,
  509. <<"ninenines.eu">>, <<"/path/NaN/">>),
  510. Dispatch2 = [{'_', [],
  511. [{[<<"path">>, username], [{username, function,
  512. fun(Value) -> Value =:= cowboy_bstr:to_lower(Value) end}],
  513. match, []}]}],
  514. {ok, _, [], [{username, <<"essen">>}], _, _} = match(Dispatch2,
  515. <<"ninenines.eu">>, <<"/path/essen">>),
  516. {error, notfound, path} = match(Dispatch2,
  517. <<"ninenines.eu">>, <<"/path/ESSEN">>),
  518. ok.
  519. match_same_bindings_test() ->
  520. Dispatch = [{[same, same], [], [{'_', [], match, []}]}],
  521. {ok, _, [], [{same, <<"eu">>}], _, _} = match(Dispatch,
  522. <<"eu.eu">>, <<"/">>),
  523. {error, notfound, host} = match(Dispatch,
  524. <<"ninenines.eu">>, <<"/">>),
  525. Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [],
  526. [{[<<"path">>, user], [], match, []}]}],
  527. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  528. <<"essen.ninenines.eu">>, <<"/path/essen">>),
  529. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  530. <<"essen.ninenines.eu">>, <<"/path/essen/">>),
  531. {error, notfound, path} = match(Dispatch2,
  532. <<"essen.ninenines.eu">>, <<"/path/notessen">>),
  533. Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}],
  534. {ok, _, [], [{same, <<"path">>}], _, _} = match(Dispatch3,
  535. <<"ninenines.eu">>, <<"/path/path">>),
  536. {error, notfound, path} = match(Dispatch3,
  537. <<"ninenines.eu">>, <<"/path/to">>),
  538. ok.
  539. -endif.