Created
November 6, 2012 10:53
-
-
Save omarkj/4024014 to your computer and use it in GitHub Desktop.
Hackney crash on closed remote socket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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