Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

3-router


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.exe

This 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-static forwards all requests with a certain prefix to a static file handler.

Next steps:

  • 4-counter counts requests, and exposes a route for getting the count.
  • 5-promise introduces Lwt, the promise library used by Dream.

Up to the tutorial index