can erlang cowboy be used as a directory index fileserver?
- User
can erlang cowboy be used as a directory index fileserver?
- Assistant
Yes, Erlang Cowboy can be used as a directory index file server, but with some custom implementation.
Cowboy itself is a small, fast, and modular HTTP server written in Erlang. While it provides the basic machinery to serve static content via
cowboy_static, it doesn't natively generate directory listings (i.e., a directory index like Apache's autoindex or nginx'sautoindex on).Options to Achieve Directory Index in Cowboy
1. Using
cowboy_staticfor Known FilesCowboy’s standard
cowboy_staticmodule can serve static files or entire directories with pre-known paths, but it doesn’t enumerate directory contents.2. Custom Handler to Serve a Directory Index
To make Cowboy serve as a directory index file server, you need to write a custom Cowboy handler that:
- Accepts a request to a directory path (e.g.,
/static/) - Reads the directory contents on disk
- Generates an HTML (or JSON) index page listing the files/folders
- Allows downloading or browsing into subdirectories
Sample outline of a custom handler:
-module(dir_index_handler). -behaviour(cowboy_handler). -export([init/2]). init(Req0, State) -> % Extract the path {Path, Req1} = cowboy_req:path(Req0), DirPath = filename:join(["/your/static/root", Path]), case file:list_dir(DirPath) of {ok, Files} -> % Generate HTML index Body = generate_index(Path, Files), Req2 = cowboy_req:reply(200, #{<<"content-type">> => <<"text/html">>}, Body, Req1), {ok, Req2, State}; {error, enoent} -> Req2 = cowboy_req:reply(404, #{<<"content-type">> => <<"text/plain">>}, <<"Not found">>, Req1), {ok, Req2, State}; {error, Reason} -> %% Handle permission errors etc. Req2 = cowboy_req:reply(500, #{<<"content-type">> => <<"text/plain">>}, io_lib:format("Error: ~p", [Reason]), Req1), {ok, Req2, State} end. generate_index(Dir, Files) -> Links = [io_lib:format("<li><a href=\"~s/~s\">~s</a></li>", [Dir, F, F]) || F <- Files], Html = [ "<html><head><title>Index of ", Dir, "</title></head><body>", "<h1>Index of ", Dir, "</h1><ul>", Links, "</ul></body></html>" ], iolist_to_binary(Html).3. Use Existing Libraries (Optional)
There may be community-contributed Cowboy handlers or utilities that do something similar. However, writing a custom handler as shown gives full control and is relatively straightforward.
Summary
Feature Support in Cowboy Serve static files ✅ Yes (via cowboy_static)Directory listing / index ❌ Not built-in Custom directory index ✅ Yes (via custom handler) 🛠️ To use Cowboy as a directory index file server, you should write a custom handler that dynamically lists and links to the files in a requested directory.
Let me know if you want a complete working example with routing.
- Accepts a request to a directory path (e.g.,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.