aboutsummaryrefslogtreecommitdiffstats
path: root/examples/file_server/src/directory_lister.erl
diff options
context:
space:
mode:
authorLoïc Hoguin <[email protected]>2016-06-13 13:23:22 +0200
committerLoïc Hoguin <[email protected]>2016-06-13 13:26:24 +0200
commit88227898edd26a823d0942fc7226adb61a20cb5d (patch)
treeaf1aeb41e7b92145b3be017cfdf18bf66f4a8e6e /examples/file_server/src/directory_lister.erl
parent4293a40d9e922bc00f25d6c7e328f86e102275a0 (diff)
downloadcowboy-88227898edd26a823d0942fc7226adb61a20cb5d.tar.gz
cowboy-88227898edd26a823d0942fc7226adb61a20cb5d.tar.bz2
cowboy-88227898edd26a823d0942fc7226adb61a20cb5d.zip
Merge static_world and web_server examples
The new example is called file_server and it's basically the same as web_server was. The name is clearer than the original, all examples being "Web servers". The new example is also tested and the test suite has been refactored a little.
Diffstat (limited to 'examples/file_server/src/directory_lister.erl')
-rw-r--r--examples/file_server/src/directory_lister.erl32
1 files changed, 32 insertions, 0 deletions
diff --git a/examples/file_server/src/directory_lister.erl b/examples/file_server/src/directory_lister.erl
new file mode 100644
index 0000000..2ca9d30
--- /dev/null
+++ b/examples/file_server/src/directory_lister.erl
@@ -0,0 +1,32 @@
+%% Feel free to use, reuse and abuse the code in this file.
+
+-module(directory_lister).
+-behaviour(cowboy_middleware).
+
+-export([execute/2]).
+
+execute(Req, Env=#{handler := cowboy_static}) ->
+ redirect_directory(Req, Env);
+execute(Req, Env) ->
+ {ok, Req, Env}.
+
+redirect_directory(Req, Env=#{handler_opts := {_, _, _, Extra}}) ->
+ Path = cowboy_req:path_info(Req),
+ Path1 = << <<S/binary, $/>> || S <- Path >>,
+ {dir_handler, DirHandler} = lists:keyfind(dir_handler, 1, Extra),
+ FullPath = resource_path(Path1),
+ case valid_path(Path) and filelib:is_dir(FullPath) of
+ true -> handle_directory(Req, Env, Path1, FullPath, DirHandler);
+ false -> {ok, Req, Env}
+ end.
+
+handle_directory(Req, Env, Prefix, Path, DirHandler) ->
+ {ok, Req, Env#{handler => DirHandler, handler_opts => {Prefix, Path}}}.
+
+valid_path([]) -> true;
+valid_path([<<"..">> | _T]) -> false;
+valid_path([<<"/", _/binary>> | _T]) -> false;
+valid_path([_H | Rest]) -> valid_path(Rest).
+
+resource_path(Path) ->
+ filename:join([code:priv_dir(file_server), Path]).