Erlang httpc GET JSON with timeouts
Erlang
-module(http_json).
-export([get_json/2]).
%% Requires OTP 27+ for the stdlib json module.
get_json(Url, TimeoutMs) ->
[application:ensure_all_started(A) || A <- [inets, ssl]],
Request = {Url, [{"accept", "application/json"}]},
HttpOpts = [{timeout, TimeoutMs}, {connect_timeout, TimeoutMs}],
case httpc:request(get, Request, HttpOpts, [{body_format, binary}]) of
{ok, {{_, 200, _}, _Headers, Body}} ->
try json:decode(Body) of
Json -> {ok, Json}
catch
error:Reason -> {error, {invalid_json, Reason}}
end;
{ok, {{_, Status, _}, _H, _B}} -> {error, {http_status, Status}};
{error, Reason} -> {error, Reason}
end.