cowboy_router.erl 22 KB

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