PageRenderTime 163ms CodeModel.GetById 80ms app.highlight 6ms RepoModel.GetById 75ms app.codeStats 0ms

/support/templates/mochiwebapp_skel/src/mochiapp_web.erl

http://github.com/basho/mochiweb
Erlang | 68 lines | 48 code | 12 blank | 8 comment | 0 complexity | 2e36c464574b374715b9706b370bd47b MD5 | raw file
 1%% @author {{author}}
 2%% @copyright {{year}} {{author}}
 3
 4%% @doc Web server for {{appid}}.
 5
 6-module({{appid}}_web).
 7-author("{{author}}").
 8
 9-export([start/1, stop/0, loop/2]).
10
11%% External API
12
13start(Options) ->
14    {DocRoot, Options1} = get_option(docroot, Options),
15    Loop = fun (Req) ->
16                   ?MODULE:loop(Req, DocRoot)
17           end,
18    mochiweb_http:start([{name, ?MODULE}, {loop, Loop} | Options1]).
19
20stop() ->
21    mochiweb_http:stop(?MODULE).
22
23loop(Req, DocRoot) ->
24    "/" ++ Path = Req:get(path),
25    try
26        case Req:get(method) of
27            Method when Method =:= 'GET'; Method =:= 'HEAD' ->
28                case Path of
29                    _ ->
30                        Req:serve_file(Path, DocRoot)
31                end;
32            'POST' ->
33                case Path of
34                    _ ->
35                        Req:not_found()
36                end;
37            _ ->
38                Req:respond({501, [], []})
39        end
40    catch
41        Type:What ->
42            Report = ["web request failed",
43                      {path, Path},
44                      {type, Type}, {what, What},
45                      {trace, erlang:get_stacktrace()}],
46            error_logger:error_report(Report),
47            Req:respond({500, [{"Content-Type", "text/plain"}],
48                         "request failed, sorry\n"})
49    end.
50
51%% Internal API
52
53get_option(Option, Options) ->
54    {proplists:get_value(Option, Options), proplists:delete(Option, Options)}.
55
56%%
57%% Tests
58%%
59-ifdef(TEST).
60-include_lib("eunit/include/eunit.hrl").
61
62you_should_write_a_test() ->
63    ?assertEqual(
64       "No, but I will!",
65       "Have you written any tests?"),
66    ok.
67
68-endif.