Skip to content

Instantly share code, notes, and snippets.

@nerdyworm
Created August 5, 2018 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nerdyworm/de57df7097500e763776536c4144f58e to your computer and use it in GitHub Desktop.
Save nerdyworm/de57df7097500e763776536c4144f58e to your computer and use it in GitHub Desktop.
Upload a file with ocaml, cohttp, and lwt without reading the entire file to memory.
open Lwt
open Cohttp
open Cohttp_lwt_unix
let read fd () =
let buffer = Bytes.create 1024 in
let%lwt len = Lwt_unix.read fd buffer 0 1024 in
match len with
| 1024 -> Lwt.return(Some (Bytes.to_string buffer))
| 0 -> Lwt.return(None)
| a -> Lwt.return(Some(Bytes.sub_string buffer 0 a))
let upload_file url path =
let%lwt fd = Lwt_unix.(openfile path [O_RDONLY] 0) in
let stream = Lwt_stream.from (read fd) in
let body = Cohttp_lwt.Body.of_stream stream in
let uri = url |> Uri.of_string in
let%lwt (resp, body) = Client.post ~body uri in
let code = resp |> Response.status |> Code.code_of_status in
match code with
| _ ->
let () = print_endline (string_of_int code) in
body |> Cohttp_lwt.Body.to_string >|= fun body ->
body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment