directory_handler.erl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. %% @doc Directory handler.
  3. -module(directory_handler).
  4. %% REST Callbacks
  5. -export([init/3]).
  6. -export([rest_init/2]).
  7. -export([allowed_methods/2]).
  8. -export([resource_exists/2]).
  9. -export([content_types_provided/2]).
  10. %% Callback Callbacks
  11. -export([list_json/2]).
  12. -export([list_html/2]).
  13. init(_Transport, _Req, _Paths) ->
  14. {upgrade, protocol, cowboy_rest}.
  15. rest_init(Req, Paths) ->
  16. {ok, Req, Paths}.
  17. allowed_methods(Req, State) ->
  18. {[<<"GET">>], Req, State}.
  19. resource_exists(Req, {ReqPath, FilePath}) ->
  20. case file:list_dir(FilePath) of
  21. {ok, Fs} -> {true, Req, {ReqPath, lists:sort(Fs)}};
  22. _Err -> {false, Req, {ReqPath, FilePath}}
  23. end.
  24. content_types_provided(Req, State) ->
  25. {[
  26. {{<<"application">>, <<"json">>, []}, list_json},
  27. {{<<"text">>, <<"html">>, []}, list_html}
  28. ], Req, State}.
  29. list_json(Req, {Path, Fs}) ->
  30. Files = [[ <<(list_to_binary(F))/binary>> || F <- Fs ]],
  31. {jsx:encode(Files), Req, Path}.
  32. list_html(Req, {Path, Fs}) ->
  33. Body = [[ links(Path, F) || F <- [".."|Fs] ]],
  34. HTML = [<<"<!DOCTYPE html><html><head><title>Index</title></head>",
  35. "<body>">>, Body, <<"</body></html>\n">>],
  36. {HTML, Req, Path}.
  37. links(<<>>, File) ->
  38. ["<a href='/", File, "'>", File, "</a><br>\n"];
  39. links(Prefix, File) ->
  40. ["<a href='/", Prefix, $/, File, "'>", File, "</a><br>\n"].