cowboy_router.erl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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 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 lists:keyfind(Name, 1, Bindings) of
  262. false ->
  263. check_constraints(Tail, Bindings);
  264. {_, Value} ->
  265. Constraints = element(2, Field),
  266. case cowboy_constraints:validate(Value, Constraints) of
  267. true ->
  268. check_constraints(Tail, Bindings);
  269. {true, Value2} ->
  270. Bindings2 = lists:keyreplace(Name, 1, Bindings,
  271. {Name, Value2}),
  272. check_constraints(Tail, Bindings2);
  273. false ->
  274. nomatch
  275. end
  276. end.
  277. -spec split_host(binary()) -> tokens().
  278. split_host(Host) ->
  279. split_host(Host, []).
  280. split_host(Host, Acc) ->
  281. case binary:match(Host, <<".">>) of
  282. nomatch when Host =:= <<>> ->
  283. Acc;
  284. nomatch ->
  285. [Host|Acc];
  286. {Pos, _} ->
  287. << Segment:Pos/binary, _:8, Rest/bits >> = Host,
  288. false = byte_size(Segment) == 0,
  289. split_host(Rest, [Segment|Acc])
  290. end.
  291. %% Following RFC2396, this function may return path segments containing any
  292. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  293. %% and part of a path segment.
  294. -spec split_path(binary()) -> tokens() | badrequest.
  295. split_path(<< $/, Path/bits >>) ->
  296. split_path(Path, []);
  297. split_path(_) ->
  298. badrequest.
  299. split_path(Path, Acc) ->
  300. try
  301. case binary:match(Path, <<"/">>) of
  302. nomatch when Path =:= <<>> ->
  303. remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- Acc]), []);
  304. nomatch ->
  305. remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- [Path|Acc]]), []);
  306. {Pos, _} ->
  307. << Segment:Pos/binary, _:8, Rest/bits >> = Path,
  308. split_path(Rest, [Segment|Acc])
  309. end
  310. catch
  311. error:badarg ->
  312. badrequest
  313. end.
  314. remove_dot_segments([], Acc) ->
  315. lists:reverse(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([<<"..">>|Segments], [_|Acc]) ->
  321. remove_dot_segments(Segments, Acc);
  322. remove_dot_segments([S|Segments], Acc) ->
  323. remove_dot_segments(Segments, [S|Acc]).
  324. -ifdef(TEST).
  325. remove_dot_segments_test_() ->
  326. Tests = [
  327. {[<<"a">>, <<"b">>, <<"c">>, <<".">>, <<"..">>, <<"..">>, <<"g">>], [<<"a">>, <<"g">>]},
  328. {[<<"mid">>, <<"content=5">>, <<"..">>, <<"6">>], [<<"mid">>, <<"6">>]},
  329. {[<<"..">>, <<"a">>], [<<"a">>]}
  330. ],
  331. [fun() -> R = remove_dot_segments(S, []) end || {S, R} <- Tests].
  332. -endif.
  333. -spec list_match(tokens(), dispatch_match(), bindings())
  334. -> {true, bindings(), undefined | tokens()} | false.
  335. %% Atom '...' matches any trailing path, stop right now.
  336. list_match(List, ['...'], Binds) ->
  337. {true, Binds, List};
  338. %% Atom '_' matches anything, continue.
  339. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  340. list_match(Tail, TailMatch, Binds);
  341. %% Both values match, continue.
  342. list_match([E|Tail], [E|TailMatch], Binds) ->
  343. list_match(Tail, TailMatch, Binds);
  344. %% Bind E to the variable name V and continue,
  345. %% unless V was already defined and E isn't identical to the previous value.
  346. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  347. case lists:keyfind(V, 1, Binds) of
  348. {_, E} ->
  349. list_match(Tail, TailMatch, Binds);
  350. {_, _} ->
  351. false;
  352. false ->
  353. list_match(Tail, TailMatch, [{V, E}|Binds])
  354. end;
  355. %% Match complete.
  356. list_match([], [], Binds) ->
  357. {true, Binds, undefined};
  358. %% Values don't match, stop.
  359. list_match(_List, _Match, _Binds) ->
  360. false.
  361. %% Tests.
  362. -ifdef(TEST).
  363. compile_test_() ->
  364. Tests = [
  365. %% Match any host and path.
  366. {[{'_', [{'_', h, o}]}],
  367. [{'_', [], [{'_', [], h, o}]}]},
  368. {[{"cowboy.example.org",
  369. [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}],
  370. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [
  371. {[], [], ha, oa},
  372. {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]},
  373. {[{'_', [{"/path/to/resource/", h, o}]}],
  374. [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]},
  375. % Cyrillic from a latin1 encoded file.
  376. {[{'_', [{[47,208,191,209,131,209,130,209,140,47,208,186,47,209,128,
  377. 208,181,209,129,209,131,209,128,209,129,209,131,47], h, o}]}],
  378. [{'_', [], [{[<<208,191,209,131,209,130,209,140>>, <<208,186>>,
  379. <<209,128,208,181,209,129,209,131,209,128,209,129,209,131>>],
  380. [], h, o}]}]},
  381. {[{"cowboy.example.org.", [{'_', h, o}]}],
  382. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]},
  383. {[{".cowboy.example.org", [{'_', h, o}]}],
  384. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]},
  385. % Cyrillic from a latin1 encoded file.
  386. {[{[208,189,208,181,208,186,208,184,208,185,46,209,129,208,176,
  387. 208,185,209,130,46,209,128,209,132,46], [{'_', h, o}]}],
  388. [{[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>,
  389. <<208,189,208,181,208,186,208,184,208,185>>],
  390. [], [{'_', [], h, o}]}]},
  391. {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}],
  392. [{[<<"org">>, <<"example">>, subdomain], [], [
  393. {[<<"hats">>, name, <<"prices">>], [], h, o}]}]},
  394. {[{"ninenines.:_", [{"/hats/:_", h, o}]}],
  395. [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]},
  396. {[{"[www.]ninenines.eu",
  397. [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [
  398. {[<<"eu">>, <<"ninenines">>], [], [
  399. {[<<"horses">>], [], h, o},
  400. {[<<"hats">>], [], h, o},
  401. {[<<"hats">>, <<"page">>, number], [], h, o}]},
  402. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  403. {[<<"horses">>], [], h, o},
  404. {[<<"hats">>], [], h, o},
  405. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  406. {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [
  407. {[<<"hats">>], [], h, o},
  408. {[<<"hats">>, <<"page">>], [], h, o},
  409. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  410. {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}],
  411. [{[<<"eu">>, <<"ninenines">>, '...'], [], [
  412. {[<<"hats">>, '...'], [], h, o}]}]}
  413. ],
  414. [{lists:flatten(io_lib:format("~p", [Rt])),
  415. fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests].
  416. split_host_test_() ->
  417. Tests = [
  418. {<<"">>, []},
  419. {<<"*">>, [<<"*">>]},
  420. {<<"cowboy.ninenines.eu">>,
  421. [<<"eu">>, <<"ninenines">>, <<"cowboy">>]},
  422. {<<"ninenines.eu">>,
  423. [<<"eu">>, <<"ninenines">>]},
  424. {<<"ninenines.eu.">>,
  425. [<<"eu">>, <<"ninenines">>]},
  426. {<<"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">>,
  427. [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>,
  428. <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>,
  429. <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>,
  430. <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]}
  431. ],
  432. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  433. split_path_test_() ->
  434. Tests = [
  435. {<<"/">>, []},
  436. {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]},
  437. {<<"/users">>, [<<"users">>]},
  438. {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]},
  439. {<<"/users/a+b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]}
  440. ],
  441. [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests].
  442. match_test_() ->
  443. Dispatch = [
  444. {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [
  445. {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []}
  446. ]},
  447. {[<<"eu">>, <<"ninenines">>], [], [
  448. {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []},
  449. {'_', [], match_extend, []}
  450. ]},
  451. {[var, <<"ninenines">>], [], [
  452. {[<<"threads">>, var], [], match_duplicate_vars,
  453. [we, {expect, two}, var, here]}
  454. ]},
  455. {[ext, <<"erlang">>], [], [
  456. {'_', [], match_erlang_ext, []}
  457. ]},
  458. {'_', [], [
  459. {[<<"users">>, id, <<"friends">>], [], match_users_friends, []},
  460. {'_', [], match_any, []}
  461. ]}
  462. ],
  463. Tests = [
  464. {<<"any">>, <<"/">>, {ok, match_any, [], []}},
  465. {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>,
  466. {ok, match_any_subdomain_users, [], []}},
  467. {<<"www.ninenines.eu">>, <<"/users/42/mails">>,
  468. {ok, match_any, [], []}},
  469. {<<"www.ninenines.eu">>, <<"/">>,
  470. {ok, match_any, [], []}},
  471. {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>,
  472. {error, notfound, path}},
  473. {<<"ninenines.eu">>, <<"/">>,
  474. {ok, match_extend, [], []}},
  475. {<<"ninenines.eu">>, <<"/users/42/friends">>,
  476. {ok, match_extend_users_friends, [], [{id, <<"42">>}]}},
  477. {<<"erlang.fr">>, '_',
  478. {ok, match_erlang_ext, [], [{ext, <<"fr">>}]}},
  479. {<<"any">>, <<"/users/444/friends">>,
  480. {ok, match_users_friends, [], [{id, <<"444">>}]}}
  481. ],
  482. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  483. {ok, Handler, Opts, Binds, undefined, undefined}
  484. = match(Dispatch, H, P)
  485. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  486. match_info_test_() ->
  487. Dispatch = [
  488. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  489. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []}
  490. ]},
  491. {[<<"eu">>, <<"ninenines">>, '...'], [], [
  492. {'_', [], match_any, []}
  493. ]},
  494. % Cyrillic from a latin1 encoded file.
  495. {[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>], [], [
  496. {[<<208,191,209,131,209,130,209,140>>, '...'], [], match_path, []}
  497. ]}
  498. ],
  499. Tests = [
  500. {<<"ninenines.eu">>, <<"/">>,
  501. {ok, match_any, [], [], [], undefined}},
  502. {<<"bugs.ninenines.eu">>, <<"/">>,
  503. {ok, match_any, [], [], [<<"bugs">>], undefined}},
  504. {<<"cowboy.bugs.ninenines.eu">>, <<"/">>,
  505. {ok, match_any, [], [], [<<"cowboy">>, <<"bugs">>], undefined}},
  506. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>,
  507. {ok, match_path, [], [], undefined, []}},
  508. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>,
  509. {ok, match_path, [], [], undefined, [<<"path_info">>]}},
  510. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>,
  511. {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}},
  512. % Cyrillic from a latin1 encoded file.
  513. {<<209,129,208,176,208,185,209,130,46,209,128,209,132>>,
  514. <<47,208,191,209,131,209,130,209,140,47,208,180,208,190,208,188,208,190,208,185>>,
  515. {ok, match_path, [], [], undefined, [<<208,180,208,190,208,188,208,190,208,185>>]}}
  516. ],
  517. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  518. R = match(Dispatch, H, P)
  519. end} || {H, P, R} <- Tests].
  520. match_constraints_test() ->
  521. Dispatch = [{'_', [],
  522. [{[<<"path">>, value], [{value, int}], match, []}]}],
  523. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  524. <<"ninenines.eu">>, <<"/path/123">>),
  525. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  526. <<"ninenines.eu">>, <<"/path/123/">>),
  527. {error, notfound, path} = match(Dispatch,
  528. <<"ninenines.eu">>, <<"/path/NaN/">>),
  529. Dispatch2 = [{'_', [], [{[<<"path">>, username],
  530. [{username, fun(Value) -> Value =:= cowboy_bstr:to_lower(Value) end}],
  531. match, []}]}],
  532. {ok, _, [], [{username, <<"essen">>}], _, _} = match(Dispatch2,
  533. <<"ninenines.eu">>, <<"/path/essen">>),
  534. {error, notfound, path} = match(Dispatch2,
  535. <<"ninenines.eu">>, <<"/path/ESSEN">>),
  536. ok.
  537. match_same_bindings_test() ->
  538. Dispatch = [{[same, same], [], [{'_', [], match, []}]}],
  539. {ok, _, [], [{same, <<"eu">>}], _, _} = match(Dispatch,
  540. <<"eu.eu">>, <<"/">>),
  541. {error, notfound, host} = match(Dispatch,
  542. <<"ninenines.eu">>, <<"/">>),
  543. Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [],
  544. [{[<<"path">>, user], [], match, []}]}],
  545. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  546. <<"essen.ninenines.eu">>, <<"/path/essen">>),
  547. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  548. <<"essen.ninenines.eu">>, <<"/path/essen/">>),
  549. {error, notfound, path} = match(Dispatch2,
  550. <<"essen.ninenines.eu">>, <<"/path/notessen">>),
  551. Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}],
  552. {ok, _, [], [{same, <<"path">>}], _, _} = match(Dispatch3,
  553. <<"ninenines.eu">>, <<"/path/path">>),
  554. {error, notfound, path} = match(Dispatch3,
  555. <<"ninenines.eu">>, <<"/path/to">>),
  556. ok.
  557. -endif.