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