%% @author author %% @copyright YYYY author. %% @doc Web server for test. -module(test_web). -author('author '). -export([start/1, stop/0, loop/2]). %% External API start(Options) -> {DocRoot, Options1} = get_option(docroot, Options), Loop = fun (Req) -> ?MODULE:loop(Req, DocRoot) end, mochiweb_http:start([{name, ?MODULE}, {loop, Loop} | Options1]). stop() -> mochiweb_http:stop(?MODULE). loop(Req, DocRoot) -> "/" ++ Path = Req:get(path), case Req:get(method) of Method when Method =:= 'GET'; Method =:= 'HEAD' -> case Path of "timer" -> %% 新增了 /timer 这个 URL,它是一个 HTTP Chunked 的例子 Response = Req:ok({"text/plain", chunked}), timer(Response); _ -> Req:serve_file(Path, DocRoot) end; 'POST' -> case Path of _ -> Req:not_found() end; _ -> Req:respond({501, [], []}) end. %% Internal API get_option(Option, Options) -> {proplists:get_value(Option, Options), proplists:delete(Option, Options)}. %% 打印当前时间,间隔一秒,再在已经打开的 http 连接之上,再次打印,这也就是所谓 HTTP长连接/ServerPush 的一种 timer(Response) -> Response:write_chunk(io_lib:format("The time is: ~p~n", [calendar:local_time()])), timer:sleep(1000), timer(Response).