Skip to content

Instantly share code, notes, and snippets.

@omarkj
Created November 6, 2012 10:53
Show Gist options
  • Save omarkj/4024014 to your computer and use it in GitHub Desktop.
Save omarkj/4024014 to your computer and use it in GitHub Desktop.
Hackney crash on closed remote socket
-module(server).
-export([server/0]).
server() ->
start(hackney),
{ok, Socket} = gen_tcp:listen(0, [binary,{active, true},
{packet, http}]),
{ok, Port} = inet:port(Socket),
spawn(fun() ->
{ok, Socket0} = gen_tcp:accept(Socket),
loop(Socket0)
end),
Url = create_url(Port),
E = hackney:request(get, Url),
io:format("Error: ~n~p", [E]).
loop(Socket) ->
receive
{http, Socket0, http_eoh} ->
Body = <<"{\"ok\":\"ok\"}">>,
BodyS = list_to_binary(integer_to_list(size(Body))),
Packet = create_packet([<<"HTTP/1.0 200 OK\n">>,
<<"Content-Type: application/json\n">>,
<<"Connection: close\n">>,
<<"Content-Length: ", BodyS/binary, "\n">>,
<<"\r\n">>,
Body
], <<>>),
ok = gen_tcp:send(Socket, Packet),
gen_tcp:close(Socket0),
ok;
{http, Socket0, _HttpPacket} ->
loop(Socket0)
end.
create_packet([], Res) ->
<<Res/binary>>;
create_packet([Part|Rest], <<>>) ->
create_packet(Rest, Part);
create_packet([Part|Rest], Res) ->
create_packet(Rest, <<Res/binary, Part/binary>>).
create_url(Port) ->
BPort = list_to_binary(integer_to_list(Port)),
<<"http://localhost:", BPort/binary>>.
start(App) ->
case application:start(App) of
{error, {not_started, Dep}} ->
start(Dep),
start(App);
{error, {already_started, _}} ->
ok;
ok ->
ok
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment