A router sends requests to
different handlers, depending on their method and path. In this example, we
still serve Good morning, world! at our site root, /. But, we have a
different response for GET requests to /echo/*, and we respond to
everything else with 404 Not Found:
let () =
Dream.run
@@ Dream.logger
@@ Dream.router [
Dream.get "/"
(fun _ ->
Dream.html "Good morning, world!");
Dream.get "/echo/:word"
(fun request ->
Dream.html (Dream.param request "word"));
]$ cd example/3-router
$ opam install --deps-only --yes .
$ dune exec --root . ./router.exeThis is also our first dynamic site! A request to /echo/foo gets the response
foo, and a request to /echo/bar gets bar!
The syntax :word in a route creates a path parameter, which can be read with
Dream.param.
When none of the routes match, the router returns a 404 Not Found response.
Except for the status code, the 404 Not Found response is completely empty,
so it might not display well in your browser. In example
9-error, we will decorate all error responses with
an error template in one central location.
The router can do more than match simple routes:
f-staticforwards all requests with a certain prefix to a static file handler.
Next steps:
4-countercounts requests, and exposes a route for getting the count.5-promiseintroduces Lwt, the promise library used by Dream.