How do I download a file with Cohttp?

I see how to access a text body, but I want to download some files and save them to disk. Because I couldn’t figure it out from the documentation. I ended up using Sys.command (Filename.quote_command "wget" [url]), but it would be nice to know how this is supposed to work. I’m on “unix” i.e. Linux.

For the lwt variant of Cohttp you can get this pretty easily by combining the body (you can get it as a stream), and the unix io modules from Lwt. Cohttp_async version will also look similar and you’d get the body as string Async_kernel.Pipe.t and you can then use the Async_unit.Writer module to write the content to disk.

open Lwt.Syntax
open Cohttp_lwt
open Cohttp_lwt_unix

let download (uri : Uri.t) (dest : string) =
  let* _resp, body = Client.get uri in
  (* TODO: check response for status codes, follow redirects if applicable *)
  let stream = Body.to_stream body in
  Lwt_io.with_file ~mode:Lwt_io.output dest (fun chan ->
      Lwt_stream.iter_s (Lwt_io.write chan) stream)
;;
4 Likes

Perfect! Thanks so much.