[Client] How to close connection without downloading response body
Is there a way to close a connection right after receiving the response headers but before downloading the body?
Current work arounds
My current solution is to use Lwt.cancel on the returned value from Cohttp_lwt_unix.Client.get after checking the response status to know whether or not I care about the body of the response. I was clued in to this solution after inspecting Cohttp_lwt.Client.Make.read_response and noticing it registers an on_cancel event listener on the Lwt promise that closes the connection. In my testing, this seems to work, but it feels hacky and that there should be a more explicit way of doing this.
Example
let check_uri uri =
let result = Cohttp_lwt_unix.Client.get uri in
let%lwt resp, body = result in
if Cohttp.Response.status resp = `OK then
let () = Lwt.cancel result in
Lwt.return @@ Ok ()
else
Lwt.return @@ Error (resp, body)
My only other idea would be to basically copy the code of call and read_response from Cohttp_lwt.Client.Make and have them return a function for closing the connection.
Why I need this
Basically, I need to test a URI to see if it will respond with an error before passing it on to other parts of the program. These URIs are for large, multi-gigabyte files and I only need to see the response status to know whether or not they're working as expected. The URIs always respond with 200 OK to HEAD requests, so that's not an option.
Fwiw, your solution is fine, maybe we should document it better. If you don't need the body you can also call Cohttp_lwt_body.drain_body body, would that do too much?
If you don't need the body you can also call
Cohttp_lwt_body.drain_body body, would that do too much?
Wouldn't that still continue downloading the response from the server even if it discards it immediately? Since I'm dealing with multi-gigabyte downloads, I'd like to avoid that.