This commit is contained in:
anlicheng 2025-09-23 11:16:31 +08:00
parent 609386cc44
commit 1f0899c85e

View File

@ -1,27 +1,16 @@
%%% docker_http.erl %%% docker_http.erl
-module(docker_http). -module(docker_http).
-export([request/4]). -export([request/4]).
-export([test/0]).
test() ->
try
Path = "/api/detail?user_id=a23147f0-2faa-40fc-b1ae-fa387bc7349f&id=16322",
catch request("GET", "/containers/json", undefined, [])
catch _:Reason:Stack ->
lager:debug("reason: ~p", [Reason]),
lager:debug("stack: ~p", [Stack])
end.
%% Unix Socket Docker API %% Unix Socket Docker API
-spec request(Method :: iolist(), Path :: string(), Body :: binary() | undefined, Headers :: list()) -> -spec request(Method :: iolist(), Path :: string(), Body :: binary() | undefined, Headers :: list()) ->
{ok, StatusCode :: integer(), RespBody :: binary()} | {error, any()}. {ok, StatusCode :: integer(), RespHeaders :: proplists:proplist(), RespBody :: binary()} | {error, any()}.
request(Method, Path, Body, Headers) when is_list(Method); is_binary(Method), is_list(Path), is_binary(Body), is_list(Headers) -> request(Method, Path, Body, Headers) when is_list(Method); is_binary(Method), is_list(Path), is_binary(Body), is_list(Headers) ->
SocketPath = "/var/run/docker.sock", SocketPath = "/var/run/docker.sock",
%% 使 gun:open/2 + {local, Path} %% 使 gun:open/2 + {local, Path}
case gun:open_unix(SocketPath, #{}) of case gun:open_unix(SocketPath, #{}) of
{ok, ConnPid} -> {ok, ConnPid} ->
{ok, _} = Res = gun:await_up(ConnPid), {ok, http} = gun:await_up(ConnPid),
lager:debug("gun up: ~p, res: ~p", [ConnPid, Res]),
%% Body undefined <<>> %% Body undefined <<>>
BodyBin = case Body of BodyBin = case Body of
undefined -> <<>>; undefined -> <<>>;
@ -29,7 +18,6 @@ request(Method, Path, Body, Headers) when is_list(Method); is_binary(Method), is
end, end,
%% HTTP %% HTTP
StreamRef = gun:request(ConnPid, Method, Path, Headers, BodyBin), StreamRef = gun:request(ConnPid, Method, Path, Headers, BodyBin),
lager:debug("stream is: ~p", [StreamRef]),
receive_response(ConnPid, StreamRef); receive_response(ConnPid, StreamRef);
{error, Reason} -> {error, Reason} ->
{error, Reason} {error, Reason}