cowboy_router.erl 22 KB

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