directory_handler.erl 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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/2]).
  6. -export([allowed_methods/2]).
  7. -export([resource_exists/2]).
  8. -export([content_types_provided/2]).
  9. %% Callback Callbacks
  10. -export([list_json/2]).
  11. -export([list_html/2]).
  12. init(Req, Paths) ->
  13. {cowboy_rest, Req, Paths}.
  14. allowed_methods(Req, State) ->
  15. {[<<"GET">>], Req, State}.
  16. resource_exists(Req, {ReqPath, FilePath}) ->
  17. case file:list_dir(FilePath) of
  18. {ok, Fs} -> {true, Req, {ReqPath, lists:sort(Fs)}};
  19. _Err -> {false, Req, {ReqPath, FilePath}}
  20. end.
  21. content_types_provided(Req, State) ->
  22. {[
  23. {{<<"application">>, <<"json">>, []}, list_json},
  24. {{<<"text">>, <<"html">>, []}, list_html}
  25. ], Req, State}.
  26. list_json(Req, {Path, Fs}) ->
  27. Files = [[ <<(list_to_binary(F))/binary>> || F <- Fs ]],
  28. {jsx:encode(Files), Req, Path}.
  29. list_html(Req, {Path, Fs}) ->
  30. Body = [[ links(Path, F) || F <- [".."|Fs] ]],
  31. HTML = [<<"<!DOCTYPE html><html><head><title>Index</title></head>",
  32. "<body>">>, Body, <<"</body></html>\n">>],
  33. {HTML, Req, Path}.
  34. links(<<>>, File) ->
  35. ["<a href='/", File, "'>", File, "</a><br>\n"];
  36. links(Prefix, File) ->
  37. ["<a href='/", Prefix, $/, File, "'>", File, "</a><br>\n"].