My MochiWeb Faq
10th of March 2009I recently started using the mochiweb web server, it is a very nicely designed library, however it does have scarce (non existent) documentation, the code is readable enough to extract what you need, but I just thought I would make a quick FAQ to save some time. I will just be adding these as I go along, and they aren"t necessarily right so feel free to correct.
How do I get at POST / GET data?
Req:parse_qs() and Req:parse_post() to get a proplist for each, Req:recv_body() will give you back the raw POST data in binary.
How do I get the IP / Port of the request?
Req:get_header_value("host") will give you back this as a string, not sure how it handles behind a revproxy for now, will update
How do I detect the client disconnecting (long polling)
Just to stop those nasty messages when the client goes to another page, I found the answer here. Listing the code because its handy.%% mochiwebs callback loop
loop(Req) ->
%% parse request or what ever
%% assume we send out something, waiting for response here
case wait_data(Req) of
{error, socket_closed} ->
%% socket has closed, need not response anymore
ok;
{error, timeout} ->
%% perform timeout response, let them call again
response(Req, timeout);
{ok, Data} ->
%% perform data response, and, let them call again
response(Req, Data)
end.
wait_data(Req) ->
Socket = Req:get(socket),
inet:setopts(Socket, [{active, once}]),
receive
{tcp_closed, Socket} ->
{error, socket_closed};
Data ->
{ok, Data}
after
&TimeOut ->
{error, timeout}
end.
Comments
There has been no comments
Post a Comment