PageRenderTime 45ms CodeModel.GetById 0ms RepoModel.GetById 0ms 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
Possible License(s): MIT
  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. Req:respond({500, [{"Content-Type", "text/plain"}],
  41. "request failed, sorry\n"})
  42. end.
  43. %% Internal API
  44. get_option(Option, Options) ->
  45. {proplists:get_value(Option, Options), proplists:delete(Option, Options)}.
  46. %%
  47. %% Tests
  48. %%
  49. -ifdef(TEST).
  50. -include_lib("eunit/include/eunit.hrl").
  51. you_should_write_a_test() ->
  52. ?assertEqual(
  53. "No, but I will!",
  54. "Have you written any tests?"),
  55. ok.
  56. -endif.