cowboy_router.erl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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, Env) ->
  149. {_, Dispatch} = lists:keyfind(dispatch, 1, Env),
  150. Host = cowboy_req:host(Req),
  151. Path = cowboy_req:path(Req),
  152. case match(Dispatch, Host, Path) of
  153. {ok, Handler, HandlerOpts, Bindings, HostInfo, PathInfo} ->
  154. Req2 = cowboy_req:set_bindings(HostInfo, PathInfo, Bindings, Req),
  155. {ok, Req2, [{handler, Handler}, {handler_opts, HandlerOpts}|Env]};
  156. {error, notfound, host} ->
  157. {stop, cowboy_req:reply(400, Req)};
  158. {error, badrequest, path} ->
  159. {stop, cowboy_req:reply(400, Req)};
  160. {error, notfound, path} ->
  161. {stop, cowboy_req:reply(404, Req)}
  162. end.
  163. %% Internal.
  164. %% Match hostname tokens and path tokens against dispatch rules.
  165. %%
  166. %% It is typically used for matching tokens for the hostname and path of
  167. %% the request against a global dispatch rule for your listener.
  168. %%
  169. %% Dispatch rules are a list of <em>{Hostname, PathRules}</em> tuples, with
  170. %% <em>PathRules</em> being a list of <em>{Path, HandlerMod, HandlerOpts}</em>.
  171. %%
  172. %% <em>Hostname</em> and <em>Path</em> are match rules and can be either the
  173. %% atom <em>'_'</em>, which matches everything, `<<"*">>', which match the
  174. %% wildcard path, or a list of tokens.
  175. %%
  176. %% Each token can be either a binary, the atom <em>'_'</em>,
  177. %% the atom '...' or a named atom. A binary token must match exactly,
  178. %% <em>'_'</em> matches everything for a single token, <em>'...'</em> matches
  179. %% everything for the rest of the tokens and a named atom will bind the
  180. %% corresponding token value and return it.
  181. %%
  182. %% The list of hostname tokens is reversed before matching. For example, if
  183. %% we were to match "www.ninenines.eu", we would first match "eu", then
  184. %% "ninenines", then "www". This means that in the context of hostnames,
  185. %% the <em>'...'</em> atom matches properly the lower levels of the domain
  186. %% as would be expected.
  187. %%
  188. %% When a result is found, this function will return the handler module and
  189. %% options found in the dispatch list, a key-value list of bindings and
  190. %% the tokens that were matched by the <em>'...'</em> atom for both the
  191. %% hostname and path.
  192. -spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary())
  193. -> {ok, module(), any(), bindings(),
  194. HostInfo::undefined | tokens(),
  195. PathInfo::undefined | tokens()}
  196. | {error, notfound, host} | {error, notfound, path}
  197. | {error, badrequest, path}.
  198. match([], _, _) ->
  199. {error, notfound, host};
  200. %% If the host is '_' then there can be no constraints.
  201. match([{'_', [], PathMatchs}|_Tail], _, Path) ->
  202. match_path(PathMatchs, undefined, Path, []);
  203. match([{HostMatch, Fields, PathMatchs}|Tail], Tokens, Path)
  204. when is_list(Tokens) ->
  205. case list_match(Tokens, HostMatch, []) of
  206. false ->
  207. match(Tail, Tokens, Path);
  208. {true, Bindings, HostInfo} ->
  209. HostInfo2 = case HostInfo of
  210. undefined -> undefined;
  211. _ -> lists:reverse(HostInfo)
  212. end,
  213. case check_constraints(Fields, Bindings) of
  214. {ok, Bindings2} ->
  215. match_path(PathMatchs, HostInfo2, Path, Bindings2);
  216. nomatch ->
  217. match(Tail, Tokens, Path)
  218. end
  219. end;
  220. match(Dispatch, Host, Path) ->
  221. match(Dispatch, split_host(Host), Path).
  222. -spec match_path([dispatch_path()],
  223. HostInfo::undefined | tokens(), binary() | tokens(), bindings())
  224. -> {ok, module(), any(), bindings(),
  225. HostInfo::undefined | tokens(),
  226. PathInfo::undefined | tokens()}
  227. | {error, notfound, path} | {error, badrequest, path}.
  228. match_path([], _, _, _) ->
  229. {error, notfound, path};
  230. %% If the path is '_' then there can be no constraints.
  231. match_path([{'_', [], Handler, Opts}|_Tail], HostInfo, _, Bindings) ->
  232. {ok, Handler, Opts, Bindings, HostInfo, undefined};
  233. match_path([{<<"*">>, _, Handler, Opts}|_Tail], HostInfo, <<"*">>, Bindings) ->
  234. {ok, Handler, Opts, Bindings, HostInfo, undefined};
  235. match_path([{PathMatch, Fields, Handler, Opts}|Tail], HostInfo, Tokens,
  236. Bindings) when is_list(Tokens) ->
  237. case list_match(Tokens, PathMatch, Bindings) of
  238. false ->
  239. match_path(Tail, HostInfo, Tokens, Bindings);
  240. {true, PathBinds, PathInfo} ->
  241. case check_constraints(Fields, PathBinds) of
  242. {ok, PathBinds2} ->
  243. {ok, Handler, Opts, PathBinds2, HostInfo, PathInfo};
  244. nomatch ->
  245. match_path(Tail, HostInfo, Tokens, Bindings)
  246. end
  247. end;
  248. match_path(_Dispatch, _HostInfo, badrequest, _Bindings) ->
  249. {error, badrequest, path};
  250. match_path(Dispatch, HostInfo, Path, Bindings) ->
  251. match_path(Dispatch, HostInfo, split_path(Path), Bindings).
  252. check_constraints([], Bindings) ->
  253. {ok, Bindings};
  254. check_constraints([Field|Tail], Bindings) when is_atom(Field) ->
  255. check_constraints(Tail, Bindings);
  256. check_constraints([Field|Tail], Bindings) ->
  257. Name = element(1, Field),
  258. case lists:keyfind(Name, 1, Bindings) of
  259. false ->
  260. check_constraints(Tail, Bindings);
  261. {_, Value} ->
  262. Constraints = element(2, Field),
  263. case cowboy_constraints:validate(Value, Constraints) of
  264. true ->
  265. check_constraints(Tail, Bindings);
  266. {true, Value2} ->
  267. Bindings2 = lists:keyreplace(Name, 1, Bindings,
  268. {Name, Value2}),
  269. check_constraints(Tail, Bindings2);
  270. false ->
  271. nomatch
  272. end
  273. end.
  274. -spec split_host(binary()) -> tokens().
  275. split_host(Host) ->
  276. split_host(Host, []).
  277. split_host(Host, Acc) ->
  278. case binary:match(Host, <<".">>) of
  279. nomatch when Host =:= <<>> ->
  280. Acc;
  281. nomatch ->
  282. [Host|Acc];
  283. {Pos, _} ->
  284. << Segment:Pos/binary, _:8, Rest/bits >> = Host,
  285. false = byte_size(Segment) == 0,
  286. split_host(Rest, [Segment|Acc])
  287. end.
  288. %% Following RFC2396, this function may return path segments containing any
  289. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  290. %% and part of a path segment.
  291. -spec split_path(binary()) -> tokens() | badrequest.
  292. split_path(<< $/, Path/bits >>) ->
  293. split_path(Path, []);
  294. split_path(_) ->
  295. badrequest.
  296. split_path(Path, Acc) ->
  297. try
  298. case binary:match(Path, <<"/">>) of
  299. nomatch when Path =:= <<>> ->
  300. lists:reverse([cow_qs:urldecode(S) || S <- Acc]);
  301. nomatch ->
  302. lists:reverse([cow_qs:urldecode(S) || S <- [Path|Acc]]);
  303. {Pos, _} ->
  304. << Segment:Pos/binary, _:8, Rest/bits >> = Path,
  305. split_path(Rest, [Segment|Acc])
  306. end
  307. catch
  308. error:badarg ->
  309. badrequest
  310. end.
  311. -spec list_match(tokens(), dispatch_match(), bindings())
  312. -> {true, bindings(), undefined | tokens()} | false.
  313. %% Atom '...' matches any trailing path, stop right now.
  314. list_match(List, ['...'], Binds) ->
  315. {true, Binds, List};
  316. %% Atom '_' matches anything, continue.
  317. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  318. list_match(Tail, TailMatch, Binds);
  319. %% Both values match, continue.
  320. list_match([E|Tail], [E|TailMatch], Binds) ->
  321. list_match(Tail, TailMatch, Binds);
  322. %% Bind E to the variable name V and continue,
  323. %% unless V was already defined and E isn't identical to the previous value.
  324. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  325. case lists:keyfind(V, 1, Binds) of
  326. {_, E} ->
  327. list_match(Tail, TailMatch, Binds);
  328. {_, _} ->
  329. false;
  330. false ->
  331. list_match(Tail, TailMatch, [{V, E}|Binds])
  332. end;
  333. %% Match complete.
  334. list_match([], [], Binds) ->
  335. {true, Binds, undefined};
  336. %% Values don't match, stop.
  337. list_match(_List, _Match, _Binds) ->
  338. false.
  339. %% Tests.
  340. -ifdef(TEST).
  341. compile_test_() ->
  342. Tests = [
  343. %% Match any host and path.
  344. {[{'_', [{'_', h, o}]}],
  345. [{'_', [], [{'_', [], h, o}]}]},
  346. {[{"cowboy.example.org",
  347. [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}],
  348. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [
  349. {[], [], ha, oa},
  350. {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]},
  351. {[{'_', [{"/path/to/resource/", h, o}]}],
  352. [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]},
  353. % Cyrillic from a latin1 encoded file.
  354. {[{'_', [{[47,208,191,209,131,209,130,209,140,47,208,186,47,209,128,
  355. 208,181,209,129,209,131,209,128,209,129,209,131,47], h, o}]}],
  356. [{'_', [], [{[<<208,191,209,131,209,130,209,140>>, <<208,186>>,
  357. <<209,128,208,181,209,129,209,131,209,128,209,129,209,131>>],
  358. [], h, o}]}]},
  359. {[{"cowboy.example.org.", [{'_', h, o}]}],
  360. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]},
  361. {[{".cowboy.example.org", [{'_', h, o}]}],
  362. [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]},
  363. % Cyrillic from a latin1 encoded file.
  364. {[{[208,189,208,181,208,186,208,184,208,185,46,209,129,208,176,
  365. 208,185,209,130,46,209,128,209,132,46], [{'_', h, o}]}],
  366. [{[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>,
  367. <<208,189,208,181,208,186,208,184,208,185>>],
  368. [], [{'_', [], h, o}]}]},
  369. {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}],
  370. [{[<<"org">>, <<"example">>, subdomain], [], [
  371. {[<<"hats">>, name, <<"prices">>], [], h, o}]}]},
  372. {[{"ninenines.:_", [{"/hats/:_", h, o}]}],
  373. [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]},
  374. {[{"[www.]ninenines.eu",
  375. [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [
  376. {[<<"eu">>, <<"ninenines">>], [], [
  377. {[<<"horses">>], [], h, o},
  378. {[<<"hats">>], [], h, o},
  379. {[<<"hats">>, <<"page">>, number], [], h, o}]},
  380. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  381. {[<<"horses">>], [], h, o},
  382. {[<<"hats">>], [], h, o},
  383. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  384. {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [
  385. {[<<"hats">>], [], h, o},
  386. {[<<"hats">>, <<"page">>], [], h, o},
  387. {[<<"hats">>, <<"page">>, number], [], h, o}]}]},
  388. {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}],
  389. [{[<<"eu">>, <<"ninenines">>, '...'], [], [
  390. {[<<"hats">>, '...'], [], h, o}]}]}
  391. ],
  392. [{lists:flatten(io_lib:format("~p", [Rt])),
  393. fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests].
  394. split_host_test_() ->
  395. Tests = [
  396. {<<"">>, []},
  397. {<<"*">>, [<<"*">>]},
  398. {<<"cowboy.ninenines.eu">>,
  399. [<<"eu">>, <<"ninenines">>, <<"cowboy">>]},
  400. {<<"ninenines.eu">>,
  401. [<<"eu">>, <<"ninenines">>]},
  402. {<<"ninenines.eu.">>,
  403. [<<"eu">>, <<"ninenines">>]},
  404. {<<"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">>,
  405. [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>,
  406. <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>,
  407. <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>,
  408. <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]}
  409. ],
  410. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  411. split_path_test_() ->
  412. Tests = [
  413. {<<"/">>, []},
  414. {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]},
  415. {<<"/users">>, [<<"users">>]},
  416. {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]},
  417. {<<"/users/a+b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]}
  418. ],
  419. [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests].
  420. match_test_() ->
  421. Dispatch = [
  422. {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [
  423. {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []}
  424. ]},
  425. {[<<"eu">>, <<"ninenines">>], [], [
  426. {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []},
  427. {'_', [], match_extend, []}
  428. ]},
  429. {[var, <<"ninenines">>], [], [
  430. {[<<"threads">>, var], [], match_duplicate_vars,
  431. [we, {expect, two}, var, here]}
  432. ]},
  433. {[ext, <<"erlang">>], [], [
  434. {'_', [], match_erlang_ext, []}
  435. ]},
  436. {'_', [], [
  437. {[<<"users">>, id, <<"friends">>], [], match_users_friends, []},
  438. {'_', [], match_any, []}
  439. ]}
  440. ],
  441. Tests = [
  442. {<<"any">>, <<"/">>, {ok, match_any, [], []}},
  443. {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>,
  444. {ok, match_any_subdomain_users, [], []}},
  445. {<<"www.ninenines.eu">>, <<"/users/42/mails">>,
  446. {ok, match_any, [], []}},
  447. {<<"www.ninenines.eu">>, <<"/">>,
  448. {ok, match_any, [], []}},
  449. {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>,
  450. {error, notfound, path}},
  451. {<<"ninenines.eu">>, <<"/">>,
  452. {ok, match_extend, [], []}},
  453. {<<"ninenines.eu">>, <<"/users/42/friends">>,
  454. {ok, match_extend_users_friends, [], [{id, <<"42">>}]}},
  455. {<<"erlang.fr">>, '_',
  456. {ok, match_erlang_ext, [], [{ext, <<"fr">>}]}},
  457. {<<"any">>, <<"/users/444/friends">>,
  458. {ok, match_users_friends, [], [{id, <<"444">>}]}}
  459. ],
  460. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  461. {ok, Handler, Opts, Binds, undefined, undefined}
  462. = match(Dispatch, H, P)
  463. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  464. match_info_test_() ->
  465. Dispatch = [
  466. {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [
  467. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []}
  468. ]},
  469. {[<<"eu">>, <<"ninenines">>, '...'], [], [
  470. {'_', [], match_any, []}
  471. ]},
  472. % Cyrillic from a latin1 encoded file.
  473. {[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>], [], [
  474. {[<<208,191,209,131,209,130,209,140>>, '...'], [], match_path, []}
  475. ]}
  476. ],
  477. Tests = [
  478. {<<"ninenines.eu">>, <<"/">>,
  479. {ok, match_any, [], [], [], undefined}},
  480. {<<"bugs.ninenines.eu">>, <<"/">>,
  481. {ok, match_any, [], [], [<<"bugs">>], undefined}},
  482. {<<"cowboy.bugs.ninenines.eu">>, <<"/">>,
  483. {ok, match_any, [], [], [<<"cowboy">>, <<"bugs">>], undefined}},
  484. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>,
  485. {ok, match_path, [], [], undefined, []}},
  486. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>,
  487. {ok, match_path, [], [], undefined, [<<"path_info">>]}},
  488. {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>,
  489. {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}},
  490. % Cyrillic from a latin1 encoded file.
  491. {<<209,129,208,176,208,185,209,130,46,209,128,209,132>>,
  492. <<47,208,191,209,131,209,130,209,140,47,208,180,208,190,208,188,208,190,208,185>>,
  493. {ok, match_path, [], [], undefined, [<<208,180,208,190,208,188,208,190,208,185>>]}}
  494. ],
  495. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  496. R = match(Dispatch, H, P)
  497. end} || {H, P, R} <- Tests].
  498. match_constraints_test() ->
  499. Dispatch = [{'_', [],
  500. [{[<<"path">>, value], [{value, int}], match, []}]}],
  501. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  502. <<"ninenines.eu">>, <<"/path/123">>),
  503. {ok, _, [], [{value, 123}], _, _} = match(Dispatch,
  504. <<"ninenines.eu">>, <<"/path/123/">>),
  505. {error, notfound, path} = match(Dispatch,
  506. <<"ninenines.eu">>, <<"/path/NaN/">>),
  507. Dispatch2 = [{'_', [], [{[<<"path">>, username],
  508. [{username, fun(Value) -> Value =:= cowboy_bstr:to_lower(Value) end}],
  509. match, []}]}],
  510. {ok, _, [], [{username, <<"essen">>}], _, _} = match(Dispatch2,
  511. <<"ninenines.eu">>, <<"/path/essen">>),
  512. {error, notfound, path} = match(Dispatch2,
  513. <<"ninenines.eu">>, <<"/path/ESSEN">>),
  514. ok.
  515. match_same_bindings_test() ->
  516. Dispatch = [{[same, same], [], [{'_', [], match, []}]}],
  517. {ok, _, [], [{same, <<"eu">>}], _, _} = match(Dispatch,
  518. <<"eu.eu">>, <<"/">>),
  519. {error, notfound, host} = match(Dispatch,
  520. <<"ninenines.eu">>, <<"/">>),
  521. Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [],
  522. [{[<<"path">>, user], [], match, []}]}],
  523. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  524. <<"essen.ninenines.eu">>, <<"/path/essen">>),
  525. {ok, _, [], [{user, <<"essen">>}], _, _} = match(Dispatch2,
  526. <<"essen.ninenines.eu">>, <<"/path/essen/">>),
  527. {error, notfound, path} = match(Dispatch2,
  528. <<"essen.ninenines.eu">>, <<"/path/notessen">>),
  529. Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}],
  530. {ok, _, [], [{same, <<"path">>}], _, _} = match(Dispatch3,
  531. <<"ninenines.eu">>, <<"/path/path">>),
  532. {error, notfound, path} = match(Dispatch3,
  533. <<"ninenines.eu">>, <<"/path/to">>),
  534. ok.
  535. -endif.