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

https://code.google.com/p/zotonic/ · Erlang · 69 lines · 48 code · 12 blank · 9 comment · 0 complexity · a0c8d26044578dd75d658636ba4e39b1 MD5 · raw file

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