cowboy_router.erl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. %% Colon on path segment start is special, otherwise allow.
  95. compile_rules(<< $:, Rest/bits >>, 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(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc)
  100. when Acc =:= <<>> ->
  101. compile_rules(Rest, S, ['...'|Segments], Rules, Acc);
  102. compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) ->
  103. compile_rules(Rest, S, ['...', Acc|Segments], Rules, Acc);
  104. compile_rules(<< $[, S, Rest/bits >>, S, Segments, Rules, Acc) ->
  105. compile_brackets(Rest, S, [Acc|Segments], Rules);
  106. compile_rules(<< $[, Rest/bits >>, S, Segments, Rules, <<>>) ->
  107. compile_brackets(Rest, S, Segments, Rules);
  108. %% Open bracket in the middle of a segment.
  109. compile_rules(<< $[, _/bits >>, _, _, _, _) ->
  110. error(badarg);
  111. %% Missing an open bracket.
  112. compile_rules(<< $], _/bits >>, _, _, _, _) ->
  113. error(badarg);
  114. compile_rules(<< C, Rest/bits >>, S, Segments, Rules, Acc) ->
  115. compile_rules(Rest, S, Segments, Rules, << Acc/binary, C >>).
  116. %% Everything past $: until the segment separator ($. for hosts,
  117. %% $/ for paths) or $[ or $] or end of binary is the binding name.
  118. compile_binding(<<>>, _, <<>>) ->
  119. error(badarg);
  120. compile_binding(Rest = <<>>, _, Acc) ->
  121. {Acc, Rest};
  122. compile_binding(Rest = << C, _/bits >>, S, Acc)
  123. when C =:= S; C =:= $[; C =:= $] ->
  124. {Acc, Rest};
  125. compile_binding(<< C, Rest/bits >>, S, Acc) ->
  126. compile_binding(Rest, S, << Acc/binary, C >>).
  127. compile_brackets(Rest, S, Segments, Rules) ->
  128. {Bracket, Rest2} = compile_brackets_split(Rest, <<>>, 0),
  129. Rules1 = compile_rules(Rest2, S, Segments, [], <<>>),
  130. Rules2 = compile_rules(<< Bracket/binary, Rest2/binary >>,
  131. S, Segments, [], <<>>),
  132. Rules ++ Rules2 ++ Rules1.
  133. %% Missing a close bracket.
  134. compile_brackets_split(<<>>, _, _) ->
  135. error(badarg);
  136. %% Make sure we don't confuse the closing bracket we're looking for.
  137. compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $[ ->
  138. compile_brackets_split(Rest, << Acc/binary, C >>, N + 1);
  139. compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $], N > 0 ->
  140. compile_brackets_split(Rest, << Acc/binary, C >>, N - 1);
  141. %% That's the right one.
  142. compile_brackets_split(<< $], Rest/bits >>, Acc, 0) ->
  143. {Acc, Rest};
  144. compile_brackets_split(<< C, Rest/bits >>, Acc, N) ->
  145. compile_brackets_split(Rest, << Acc/binary, C >>, N).
  146. -spec execute(Req, Env)
  147. -> {ok, Req, Env} | {stop, Req}
  148. when Req::cowboy_req:req(), Env::cowboy_middleware:env().
  149. execute(Req=#{host := Host, path := Path}, Env=#{dispatch := Dispatch}) ->
  150. case match(Dispatch, Host, Path) of
  151. {ok, Handler, HandlerOpts, Bindings, HostInfo, PathInfo} ->
  152. {ok, Req#{
  153. host_info => HostInfo,
  154. path_info => PathInfo,
  155. bindings => Bindings
  156. }, Env#{
  157. handler => Handler,
  158. handler_opts => HandlerOpts
  159. }};
  160. {error, notfound, host} ->
  161. {stop, cowboy_req:reply(400, Req)};
  162. {error, badrequest, path} ->
  163. {stop, cowboy_req:reply(400, Req)};
  164. {error, notfound, path} ->
  165. {stop, cowboy_req:reply(404, Req)}
  166. end.
  167. %% Internal.
  168. %% Match hostname tokens and path tokens against dispatch rules.
  169. %%
  170. %% It is typically used for matching tokens for the hostname and path of
  171. %% the request against a global dispatch rule for your listener.
  172. %%
  173. %% Dispatch rules are a list of <em>{Hostname, PathRules}</em> tuples, with
  174. %% <em>PathRules</em> being a list of <em>{Path, HandlerMod, HandlerOpts}</em>.
  175. %%
  176. %% <em>Hostname</em> and <em>Path</em> are match rules and can be either the
  177. %% atom <em>'_'</em>, which matches everything, `<<"*">>', which match the
  178. %% wildcard path, or a list of tokens.
  179. %%
  180. %% Each token can be either a binary, the atom <em>'_'</em>,
  181. %% the atom '...' or a named atom. A binary token must match exactly,
  182. %% <em>'_'</em> matches everything for a single token, <em>'...'</em> matches
  183. %% everything for the rest of the tokens and a named atom will bind the
  184. %% corresponding token value and return it.
  185. %%
  186. %% The list of hostname tokens is reversed before matching. For example, if
  187. %% we were to match "www.ninenines.eu", we would first match "eu", then
  188. %% "ninenines", then "www". This means that in the context of hostnames,
  189. %% the <em>'...'</em> atom matches properly the lower levels of the domain
  190. %% as would be expected.
  191. %%
  192. %% When a result is found, this function will return the handler module and
  193. %% options found in the dispatch list, a key-value list of bindings and
  194. %% the tokens that were matched by the <em>'...'</em> atom for both the
  195. %% hostname and path.
  196. -spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary())
  197. -> {ok, module(), any(), bindings(),
  198. HostInfo::undefined | tokens(),
  199. PathInfo::undefined | tokens()}
  200. | {error, notfound, host} | {error, notfound, path}
  201. | {error, badrequest, path}.
  202. match([], _, _) ->
  203. {error, notfound, host};
  204. %% If the host is '_' then there can be no constraints.
  205. match([{'_', [], PathMatchs}|_Tail], _, Path) ->
  206. match_path(PathMatchs, undefined, Path, #{});
  207. match([{HostMatch, Fields, PathMatchs}|Tail], Tokens, Path)
  208. when is_list(Tokens) ->
  209. case list_match(Tokens, HostMatch, #{}) of
  210. false ->
  211. match(Tail, Tokens, Path);
  212. {true, Bindings, HostInfo} ->
  213. HostInfo2 = case HostInfo of
  214. undefined -> undefined;
  215. _ -> lists:reverse(HostInfo)
  216. end,
  217. case check_constraints(Fields, Bindings) of
  218. {ok, Bindings2} ->
  219. match_path(PathMatchs, HostInfo2, Path, Bindings2);
  220. nomatch ->
  221. match(Tail, Tokens, Path)
  222. end
  223. end;
  224. match(Dispatch, Host, Path) ->
  225. match(Dispatch, split_host(Host), Path).
  226. -spec match_path([dispatch_path()],
  227. HostInfo::undefined | tokens(), binary() | tokens(), bindings())
  228. -> {ok, module(), any(), bindings(),
  229. HostInfo::undefined | tokens(),
  230. PathInfo::undefined | tokens()}
  231. | {error, notfound, path} | {error, badrequest, path}.
  232. match_path([], _, _, _) ->
  233. {error, notfound, path};
  234. %% If the path is '_' then there can be no constraints.
  235. match_path([{'_', [], Handler, Opts}|_Tail], HostInfo, _, Bindings) ->
  236. {ok, Handler, Opts, Bindings, HostInfo, undefined};
  237. match_path([{<<"*">>, _, Handler, Opts}|_Tail], HostInfo, <<"*">>, Bindings) ->
  238. {ok, Handler, Opts, Bindings, HostInfo, undefined};
  239. match_path([_|Tail], HostInfo, <<"*">>, Bindings) ->
  240. match_path(Tail, HostInfo, <<"*">>, Bindings);
  241. match_path([{PathMatch, Fields, Handler, Opts}|Tail], HostInfo, Tokens,
  242. Bindings) when is_list(Tokens) ->
  243. case list_match(Tokens, PathMatch, Bindings) of
  244. false ->
  245. match_path(Tail, HostInfo, Tokens, Bindings);
  246. {true, PathBinds, PathInfo} ->
  247. case check_constraints(Fields, PathBinds) of
  248. {ok, PathBinds2} ->
  249. {ok, Handler, Opts, PathBinds2, HostInfo, PathInfo};
  250. nomatch ->
  251. match_path(Tail, HostInfo, Tokens, Bindings)
  252. end
  253. end;
  254. match_path(_Dispatch, _HostInfo, badrequest, _Bindings) ->
  255. {error, badrequest, path};
  256. match_path(Dispatch, HostInfo, Path, Bindings) ->
  257. match_path(Dispatch, HostInfo, split_path(Path), Bindings).
  258. check_constraints([], Bindings) ->
  259. {ok, Bindings};
  260. check_constraints([Field|Tail], Bindings) when is_atom(Field) ->
  261. check_constraints(Tail, Bindings);
  262. check_constraints([Field|Tail], Bindings) ->
  263. Name = element(1, Field),
  264. case Bindings of
  265. #{Name := Value0} ->
  266. Constraints = element(2, Field),
  267. case cowboy_constraints:validate(Value0, Constraints) of
  268. {ok, Value} ->
  269. check_constraints(Tail, Bindings#{Name => Value});
  270. {error, _} ->
  271. nomatch
  272. end;
  273. _ ->
  274. check_constraints(Tail, Bindings)
  275. end.
  276. -spec split_host(binary()) -> tokens().
  277. split_host(Host) ->
  278. split_host(Host, []).
  279. split_host(Host, Acc) ->
  280. case binary:match(Host, <<".">>) of
  281. nomatch when Host =:= <<>> ->
  282. Acc;
  283. nomatch ->
  284. [Host|Acc];
  285. {Pos, _} ->
  286. << Segment:Pos/binary, _:8, Rest/bits >> = Host,
  287. false = byte_size(Segment) == 0,
  288. split_host(Rest, [Segment|Acc])
  289. end.
  290. %% Following RFC2396, this function may return path segments containing any
  291. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  292. %% and part of a path segment.
  293. -spec split_path(binary()) -> tokens() | badrequest.
  294. split_path(<< $/, Path/bits >>) ->
  295. split_path(Path, []);
  296. split_path(_) ->
  297. badrequest.
  298. split_path(Path, Acc) ->
  299. try
  300. case binary:match(Path, <<"/">>) of
  301. nomatch when Path =:= <<>> ->
  302. remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- Acc]), []);
  303. nomatch ->
  304. remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- [Path|Acc]]), []);
  305. {Pos, _} ->
  306. << Segment:Pos/binary, _:8, Rest/bits >> = Path,
  307. split_path(Rest, [Segment|Acc])
  308. end
  309. catch error:_ ->
  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">>, 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. %% Path segment containing a colon.
  414. {[{'_', [{"/foo/bar:blah", h, o}]}], [{'_', [], [
  415. {[<<"foo">>, <<"bar:blah">>], [], h, o}]}]}
  416. ],
  417. [{lists:flatten(io_lib:format("~p", [Rt])),
  418. fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests].
  419. split_host_test_() ->
  420. Tests = [
  421. {<<"">>, []},
  422. {<<"*">>, [<<"*">>]},
  423. {<<"cowboy.ninenines.eu">>,
  424. [<<"eu">>, <<"ninenines">>, <<"cowboy">>]},
  425. {<<"ninenines.eu">>,
  426. [<<"eu">>, <<"ninenines">>]},
  427. {<<"ninenines.eu.">>,
  428. [<<"eu">>, <<"ninenines">>]},
  429. {<<"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">>,
  430. [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>,
  431. <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>,
  432. <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>,
  433. <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]}
  434. ],
  435. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  436. split_path_test_() ->
  437. Tests = [
  438. {<<"/">>, []},
  439. {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]},
  440. {<<"/users">>, [<<"users">>]},
  441. {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]},
  442. {<<"/users/a%20b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]}
  443. ],
  444. [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests].
  445. match_test_() ->
  446. Dispatch = [
  447. {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [
  448. {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []}
  449. ]},
  450. {[<<"eu">>, <<"ninenines">>], [], [
  451. {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []},
  452. {'_', [], match_extend, []}
  453. ]},
  454. {[var, <<"ninenines">>], [], [
  455. {[<<"threads">>, var], [], match_duplicate_vars,
  456. [we, {expect, two}, var, here]}
  457. ]},
  458. {[ext, <<"erlang">>], [], [
  459. {'_', [], match_erlang_ext, []}
  460. ]},
  461. {'_', [], [
  462. {[<<"users">>, id, <<"friends">>], [], match_users_friends, []},
  463. {'_', [], match_any, []}
  464. ]}
  465. ],
  466. Tests = [
  467. {<<"any">>, <<"/">>, {ok, match_any, [], #{}}},
  468. {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>,
  469. {ok, match_any_subdomain_users, [], #{}}},
  470. {<<"www.ninenines.eu">>, <<"/users/42/mails">>,
  471. {ok, match_any, [], #{}}},
  472. {<<"www.ninenines.eu">>, <<"/">>,
  473. {ok, match_any, [], #{}}},
  474. {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>,
  475. {error, notfound, path}},
  476. {<<"ninenines.eu">>, <<"/">>,
  477. {ok, match_extend, [], #{}}},
  478. {<<"ninenines.eu">>, <<"/users/42/friends">>,
  479. {ok, match_extend_users_friends, [], #{id => <<"42">>}}},
  480. {<<"erlang.fr">>, '_',
  481. {ok, match_erlang_ext, [], #{ext => <<"fr">>}}},
  482. {<<"any">>, <<"/users/444/friends">>,
  483. {ok, match_users_friends, [], #{id => <<"444">>}}}
  484. ],
  485. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  486. {ok, Handler, Opts, Binds, undefined, undefined}
  487. = match(Dispatch, H, P)
  488. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  489. match_info_test_() ->
  490. Dispatch = [
  491. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  492. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []}
  493. ]},
  494. {[<<"eu">>, <<"ninenines">>, '...'], [], [
  495. {'_', [], match_any, []}
  496. ]}
  497. ],
  498. Tests = [
  499. {<<"ninenines.eu">>, <<"/">>,
  500. {ok, match_any, [], #{}, [], undefined}},
  501. {<<"bugs.ninenines.eu">>, <<"/">>,
  502. {ok, match_any, [], #{}, [<<"bugs">>], undefined}},
  503. {<<"cowboy.bugs.ninenines.eu">>, <<"/">>,
  504. {ok, match_any, [], #{}, [<<"cowboy">>, <<"bugs">>], undefined}},
  505. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>,
  506. {ok, match_path, [], #{}, undefined, []}},
  507. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>,
  508. {ok, match_path, [], #{}, undefined, [<<"path_info">>]}},
  509. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>,
  510. {ok, match_path, [], #{}, undefined, [<<"foo">>, <<"bar">>]}}
  511. ],
  512. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  513. R = match(Dispatch, H, P)
  514. end} || {H, P, R} <- Tests].
  515. match_constraints_test() ->
  516. Dispatch = [{'_', [],
  517. [{[<<"path">>, value], [{value, int}], match, []}]}],
  518. {ok, _, [], #{value := 123}, _, _} = match(Dispatch,
  519. <<"ninenines.eu">>, <<"/path/123">>),
  520. {ok, _, [], #{value := 123}, _, _} = match(Dispatch,
  521. <<"ninenines.eu">>, <<"/path/123/">>),
  522. {error, notfound, path} = match(Dispatch,
  523. <<"ninenines.eu">>, <<"/path/NaN/">>),
  524. Dispatch2 = [{'_', [], [{[<<"path">>, username],
  525. [{username, fun(_, Value) ->
  526. case cowboy_bstr:to_lower(Value) of
  527. Value -> {ok, Value};
  528. _ -> {error, not_lowercase}
  529. end end}],
  530. match, []}]}],
  531. {ok, _, [], #{username := <<"essen">>}, _, _} = match(Dispatch2,
  532. <<"ninenines.eu">>, <<"/path/essen">>),
  533. {error, notfound, path} = match(Dispatch2,
  534. <<"ninenines.eu">>, <<"/path/ESSEN">>),
  535. ok.
  536. match_same_bindings_test() ->
  537. Dispatch = [{[same, same], [], [{'_', [], match, []}]}],
  538. {ok, _, [], #{same := <<"eu">>}, _, _} = match(Dispatch,
  539. <<"eu.eu">>, <<"/">>),
  540. {error, notfound, host} = match(Dispatch,
  541. <<"ninenines.eu">>, <<"/">>),
  542. Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [],
  543. [{[<<"path">>, user], [], match, []}]}],
  544. {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2,
  545. <<"essen.ninenines.eu">>, <<"/path/essen">>),
  546. {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2,
  547. <<"essen.ninenines.eu">>, <<"/path/essen/">>),
  548. {error, notfound, path} = match(Dispatch2,
  549. <<"essen.ninenines.eu">>, <<"/path/notessen">>),
  550. Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}],
  551. {ok, _, [], #{same := <<"path">>}, _, _} = match(Dispatch3,
  552. <<"ninenines.eu">>, <<"/path/path">>),
  553. {error, notfound, path} = match(Dispatch3,
  554. <<"ninenines.eu">>, <<"/path/to">>),
  555. ok.
  556. -endif.