Http Client in OCaml

Here’s an idiomatic OCaml example demonstrating an HTTP client, similar to the concept shown in the Go example:

open Lwt
open Cohttp_lwt_unix
open Cohttp

let main () =
  (* Make an HTTP GET request *)
  Client.get (Uri.of_string "https://ocaml.org") >>= fun (resp, body) ->

  (* Print the HTTP response status *)
  let status = Response.status resp in
  Printf.printf "Response status: %s\n" (Code.string_of_status status);

  (* Read the response body *)
  body |> Cohttp_lwt.Body.to_string >|= fun body ->

  (* Print the first 5 lines of the response body *)
  let lines = String.split_on_char '\n' body in
  List.iteri (fun i line ->
    if i < 5 then Printf.printf "%s\n" line
  ) lines

let () =
  Lwt_main.run (main ())

This OCaml program demonstrates how to make an HTTP GET request and process the response using the cohttp library. Here’s a breakdown of the code:

  1. We open the necessary modules: Lwt for asynchronous programming, Cohttp_lwt_unix for the HTTP client, and Cohttp for HTTP-related types.

  2. The main function is defined using OCaml’s lightweight threads (Lwt). It performs the following steps:

    • Makes an HTTP GET request to “https://ocaml.org” using Client.get.
    • Prints the HTTP response status.
    • Reads the response body.
    • Prints the first 5 lines of the response body.
  3. The >>= and >|= operators are used for monadic binding in Lwt, allowing us to chain asynchronous operations.

  4. We use pattern matching to destructure the response tuple into resp and body.

  5. The response status is extracted and printed using Response.status and Code.string_of_status.

  6. The response body is converted to a string using Cohttp_lwt.Body.to_string.

  7. We split the body into lines and use List.iteri to print the first 5 lines.

  8. Finally, we run the main function using Lwt_main.run.

To run this program, you’ll need to have OCaml and the necessary libraries installed. You can install the required packages using OPAM:

opam install lwt cohttp-lwt-unix

Save the code in a file named http_client.ml and compile it using ocamlbuild:

ocamlbuild -pkg cohttp-lwt-unix http_client.native

Then run the compiled program:

./http_client.native

This example showcases OCaml’s functional programming features, its concise syntax, and the use of the Lwt library for asynchronous operations. It demonstrates how to perform HTTP requests and handle responses in a idiomatic OCaml style.