I am a rookie in Erlang, tired to write the code for spider:
-module(http).
-compile([export_all]).
init() ->
ssl:start(),
inets:start(),
register(m, spawn(fun() -> loop() end)),
register(fetch, spawn(fun() -> x() end)),
ok.
start() ->
L1 = [114689,114688,114691,114690], % detail page id
lists:map(fun(Gid) ->
io:format("~p ~n", [Gid]),
fetch ! {go, Gid}
end, L1),
m ! done,
done.
main(_) ->
init(),
start().
loop() ->
io:fwrite("this is in loop!!"),
receive
{no_res, Gid} ->
io:format("~p no res ! ~n", [Gid]),
loop();
{have_res, Gid} ->
io:format("~p have res ! ~n", [Gid]),
loop();
done ->
io:format("wowowow", [])
end.
x() ->
receive
{go, Gid} ->
http_post(Gid);
_ ->
ready
end.
http_post(Gid) ->
URL = "https://example.com", % url demo
Type = "application/json",
ReqArr = ["[{\"id\": \"", integer_to_list(Gid), "\"}]"],
ReqBody = string:join(ReqArr, ""),
case httpc:request(post, {URL, [], Type, ReqBody}, [], []) of
{ok, {_, _, ResBody}} ->
if
length(ResBody) =:= 0 ->
io:format("Y: ~p ~n", [Gid]);
m ! {no_res, Gid};
true ->
io:format("N: ~p ~n", [Gid])
m ! {have_res, Gid}
end;
{error, Reason} ->
io:format("error cause ~p~n", [Reason]);
_ ->
io:format("error cause ~n", [])
end.
Now, when I exceute code, process will terminate at once, log:
I have two question:
- How I solve this problem ?
- If I have tens of thousands of id in
L1
, how solve? Spawn dozens of actors? If yes, how do you decide which actor toreceive
which id?