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                  "hello_world" ->
30                    Req:respond({200, [{"Content-Type", "text/plain"}],
31                    "Hello world!\n"});
32                    _ ->
33                        Req:serve_file(Path, DocRoot)
34                end;
35            'POST' ->
36                case Path of
37                    _ ->
38                        Req:not_found()
39                end;
40            _ ->
41                Req:respond({501, [], []})
42        end
43    catch
44        Type:What ->
45            Report = ["web request failed",
46                      {path, Path},
47                      {type, Type}, {what, What},
48                      {trace, erlang:get_stacktrace()}],
49            error_logger:error_report(Report),
50            Req:respond({500, [{"Content-Type", "text/plain"}],
51                         "request failed, sorry\n"})
52    end.
53
54%% Internal API
55
56get_option(Option, Options) ->
57    {proplists:get_value(Option, Options), proplists:delete(Option, Options)}.
58
59%%
60%% Tests
61%%
62-ifdef(TEST).
63-include_lib("eunit/include/eunit.hrl").
64
65you_should_write_a_test() ->
66    ?assertEqual(
67       "No, but I will!",
68       "Have you written any tests?"),
69    ok.
70
71-endif.
72