OCaml GET JSON through curl with a hard timeout
OCaml
(* OCaml's stdlib has no HTTP client; shelling out to curl adds no dependencies. *)
let http_get_json ~url ~timeout ~key =
let cmd = Printf.sprintf "curl -fsS --max-time %g %s" timeout (Filename.quote url) in
let ic = Unix.open_process_in cmd in
let body = In_channel.input_all ic in
match Unix.close_process_in ic with
| Unix.WEXITED 0 ->
let q = String.make 1 '"' in
let needle = q ^ key ^ q ^ ":" ^ q in
let width = String.length needle in
let rec seek i =
if i + width > String.length body then Error (Printf.sprintf "missing JSON field %S" key)
else if String.sub body i width = needle then
match String.index_from_opt body (i + width) '"' with
| Some stop -> Ok (String.sub body (i + width) (stop - i - width))
| None -> Error (Printf.sprintf "unterminated value for %S" key)
else seek (i + 1)
in
seek 0
| _ -> Error (Printf.sprintf "GET %s failed or timed out" url)