Start a Web Server With a 'Hello World' Endpoint using cohttp-lwt-unix

Task

Web Programming / Running a Web Server / Start a Web Server With a 'Hello World' Endpoint

Opam Packages Used

  • cohttp-lwt-unix Tested with version: 5.3.0 — Used libraries: cohttp-lwt-unix
  • lwt Tested with version: 5.7.0 — Used libraries: lwt, lwt.infix

Code

The server:

  • Handles any incoming request on port 8080
  • Responds with a static Hello world message
  • Uses Server.respond_string to return a simple text response Lwt (Lwt.Infix) is used for chaining asynchronous computations
open Lwt.Infix
open Cohttp_lwt_unix

let () =
  let callback _conn _req body =
    Cohttp_lwt.Body.drain_body body >>= fun () -> 
    Server.respond_string ~status:`OK ~body:"Hello world" ()
  in
  let server = Server.make ~callback () in
  let port = 8080 in
  let mode = `TCP (`Port port) in
  Format.printf "listening on http://localhost:%d\n%!" port;
  Server.create ~mode server |> Lwt_main.run

Discussion

This example shows how to use cohttp-lwt-unix to start an HTTP server in OCaml using Lwt

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

Open an issue or contribute to this recipe!

Other Recipes for this Task