Start a Web Server That Serves an HTML Template using dream

Task

Web Programming / Running a Web Server / Start a Web Server That Serves an HTML Template

Opam Packages Used

  • dream Tested with version: 1.0.0~alpha8 — Used libraries: dream

Code

The server:

  • Handles any incoming request on port 8080
  • Logs requests
  • Responds with a static HTML template that displays "Hello World!"
  • Returns 404 error for other routes

let template =
  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Template Page</title>
    </head>
    <body>
      <h1>Hello World!</h1>
    </body>
  </html>

let () =
  Dream.run
  @@ Dream.logger
  @@ Dream.router [
    Dream.get "/" (fun _ -> Dream.html template);
  ]

Discussion

This example uses Dream, a simple and type-safe web framework for OCaml. To avoid errors, the file name should end with .eml.ml. Set the dune file following the guide here: Dream Template

Recipe not working? Comments not clear or out of date?

Open an issue or contribute to this recipe!

Other Recipes for this Task