Context in OCaml

Here’s the translation of the Go code to OCaml, with explanations in Markdown format suitable for Hugo:

Our previous example demonstrated setting up a simple HTTP server. HTTP servers are useful for showcasing the usage of contexts for controlling cancellation. A context carries deadlines, cancellation signals, and other request-scoped values across API boundaries and threads.

open Lwt
open Cohttp_lwt_unix

let hello _conn req body =
  let open Lwt.Infix in
  
  (* A context is created for each request by the Cohttp machinery *)
  let ctx = Request.ctx req in
  
  Lwt_io.printf "server: hello handler started\n" >>= fun () ->
  Lwt.finalize
    (fun () ->
      (* Simulate some work the server is doing *)
      Lwt_unix.sleep 10.0 >>= fun () ->
      Server.respond_string ~status:`OK ~body:"hello\n" ())
    (fun () -> Lwt_io.printf "server: hello handler ended\n")

let server =
  Server.create ~mode:(`TCP (`Port 8090)) (Server.make ~callback:hello ())

let () =
  ignore (Lwt_main.run server)

In this OCaml version, we’re using the Lwt library for asynchronous programming and the Cohttp library for HTTP functionality. These provide similar capabilities to Go’s concurrency model and HTTP server.

The hello function is our request handler. It simulates a long-running operation by sleeping for 10 seconds before responding. In a real-world scenario, this could represent some intensive computation or I/O operation.

Unlike Go, OCaml doesn’t have built-in cancellation contexts. However, Lwt provides cancellation capabilities through its Lwt.cancel function and Lwt.catch for handling cancellations. In a more complex scenario, you could implement cancellation by using Lwt’s cancellation features.

To run the server:

$ ocaml context.ml &

To simulate a client request to /hello, you can use curl. However, OCaml’s Cohttp server doesn’t have built-in support for cancellation upon client disconnect. In a real-world application, you’d need to implement this functionality manually using Lwt’s cancellation features.

$ curl localhost:8090/hello
server: hello handler started
hello
server: hello handler ended

This example demonstrates how to create a simple HTTP server in OCaml that can handle long-running operations. While it doesn’t directly translate Go’s context cancellation, it provides a foundation for implementing similar functionality using OCaml’s asynchronous programming constructs.