我采用了牛仔示例代码并将其破坏。
默认请求处理程序的代码如下所示:
-module(default_handler).
-behaviour(cowboy_http_handler).
-export([init/3, handle/2, terminate/2]).
init({_Any, http}, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{ok, Req2} = cowboy_http_req:reply(200, [], <<"Hello world!">>, Req),
{ok, Req2, State}.
terminate(_Req, _State) ->
ok.
它直截了当,但我想制作返回文件,所以我将其更改为:
-module(default_handler).
-behaviour(cowboy_http_handler).
-export([init/3, handle/2, terminate/2]).
init({_Any, http}, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
try
{Path, Req1} = cowboy_http_req:path(Req),
{ok, File} = file:read_file(Path),
cowboy_http_req:reply(200, [], File, Req1)
of
{ok, Req2} ->
{ok, Req2, State}
catch
_ ->
{ok, Req3} = cowboy_http_req:reply(200, [], <<"Hello world!">>, Req),
{ok, Req3, State}
end.
terminate(_Req, _State) ->
ok.
try-catch 应该处理可能没有文件的事实,但事实并非如此。这是为什么?
当我尝试获取一个不存在的文件时,我在控制台中收到一个很大的错误报告,谁能告诉我为什么?
=ERROR REPORT==== 15-Jun-2012::14:24:54 ===
** Handler default_handler terminating in handle/2
for the reason error:{badmatch,{error,badarg}}
** Options were []
** Handler state was undefined
** Request was [{socket,#Port<0.1515>},
{transport,cowboy_tcp_transport},
{connection,keepalive},
{pid,<0.1175.0>},
{method,'GET'},
{version,{1,1}},
{peer,undefined},
{host,[<<"localhost">>]},
{host_info,undefined},
{raw_host,<<"localhost">>},
{port,8080},
{path,[<<"favicon.ico">>]},
{path_info,undefined},
{raw_path,<<"/favicon.ico">>},
{qs_vals,undefined},
{raw_qs,<<>>},
{bindings,[]},
{headers,
[{'Accept-Charset',<<"ISO-8859-1,utf-8;q=0.7,*;q=0.3">>},
{'Accept-Language',<<"en-US,en;q=0.8">>},
{'Accept-Encoding',<<"gzip,deflate,sdch">>},
{'User-Agent',
<<"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/10.10 Chromium/18.0.1025.151 Chrome/18.0.1025.151 Safari/535.19">>},
{'Accept',<<"*/*">>},
{'Connection',<<"keep-alive">>},
{'Host',<<"localhost">>}]},
{p_headers,[{'Connection',[<<"keep-alive">>]}]},
{cookies,undefined},
{meta,[]},
{body_state,waiting},
{buffer,<<>>},
{resp_state,waiting},
{resp_headers,[]},
{resp_body,<<>>},
{onresponse,undefined},
{urldecode,{#Fun<cowboy_http.urldecode.2>,crash}}]
** Stacktrace: [{default_handler,handle,2,
[{file,"src/default_handler.erl"},{line,13}]},
{cowboy_http_protocol,handler_handle,3,
[{file,"src/cowboy_http_protocol.erl"},
{line,298}]}]