Absolutely! Here’s a minimal, complete Cowboy application in Erlang that serves static…
- User
Absolutely! Here’s a minimal, complete Cowboy application in Erlang that serves static files from
./public/and provides a directory index (listing) when a directory is requested.This example uses Cowboy 2.x and rebar3 as the build tool.
1. Project Structure
cowboy_dirindex/ ├── rebar.config ├── src/ │ ├── cowboy_dirindex_app.erl │ ├── cowboy_dirindex_sup.erl │ └── dir_index_handler.erl └── public/ ├── index.html └── (other files and folders)
2. rebar.config
{erl_opts, [debug_info]}. {deps, [ {cowboy, {hex, cowboy, "2.10.0"}} ]}. {shell, [ {apps, [cowboy_dirindex]} ]}.
3. Application Module (
src/cowboy_dirindex_app.erl)-module(cowboy_dirindex_app). -behaviour(application). -export([start/2, stop/1]). start(_Type, _Args) -> cowboy_dirindex_sup:start_link(). stop(_State) -> ok.
4. Supervisor (
src/cowboy_dirindex_sup.erl)-module(cowboy_dirindex_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> Dispatch = cowboy_router:compile([ {'_', [ {"/[...]", dir_index_handler, []} ]} ]), {ok, _} = cowboy:start_clear(http_listener, [{port, 8080}], #{env => #{dispatch => Dispatch}} ), {ok, {{one_for_one, 10, 10}, []}}.
5. Directory Index Handler (
src/dir_index_handler.erl)-module(dir_index_handler). -behaviour(cowboy_handler). -export([init/2]). -define(PUBLIC_DIR, "public"). init(Req, _State) -> {PathInfo, Req2} = cowboy_req:binding('...', Req), RelPath = filename:join([?PUBLIC_DIR | PathInfo]), case file:read_file_info(RelPath) of {ok, #file_info{type = directory}} -> case file:list_dir(RelPath) of {ok, Files} -> Body = render_dir_listing(PathInfo, Files), {ok, cowboy_req:reply(200, #{<<"content-type">> => <<"text/html">>}, Body, Req2), state}; {error, _} -> {ok, cowboy_req:reply(403, #{}, <<"Forbidden">>, Req2), state} end; {ok, #file_info{type = regular}} -> case file:read_file(RelPath) of {ok, Bin} -> Mime = guess_mime(RelPath), {ok, cowboy_req:reply(200, #{<<"content-type">> => Mime}, Bin, Req2), state}; {error, _} -> {ok, cowboy_req:reply(404, #{}, <<"Not found">>, Req2), state} end; _ -> {ok, cowboy_req:reply(404, #{}, <<"Not found">>, Req2), state} end. render_dir_listing(PathInfo, Files) -> Path = "/" ++ string:join([unicode:characters_to_list(P) || P <- PathInfo], "/"), Parent = case PathInfo of [] -> ""; _ -> "<li><a href=\"../\">../</a></li>" end, FileLinks = [io_lib:format("<li><a href=\"~s/\">~s/</a></li>", [F, F]) || F <- Files, is_dir(PathInfo, F)] ++ [io_lib:format("<li><a href=\"~s\">~s</a></li>", [F, F]) || F <- Files, not is_dir(PathInfo, F)], List = string:join([Parent | [lists:flatten(L) || L <- FileLinks]], "\n"), lists:flatten(io_lib:format( "<html><head><title>Index of ~s</title></head><body><h1>Index of ~s</h1><ul>~s</ul></body></html>", [Path, Path, List] )). is_dir(PathInfo, F) -> FullPath = filename:join([?PUBLIC_DIR | PathInfo] ++ [F]), case file:read_file_info(FullPath) of {ok, #file_info{type = directory}} -> true; _ -> false end. guess_mime(Filename) -> case filename:extension(Filename) of ".html" -> <<"text/html">>; ".htm" -> <<"text/html">>; ".txt" -> <<"text/plain">>; ".jpg" -> <<"image/jpeg">>; ".jpeg" -> <<"image/jpeg">>; ".png" -> <<"image/png">>; ".gif" -> <<"image/gif">>; ".css" -> <<"text/css">>; ".js" -> <<"application/javascript">>; _ -> <<"application/octet-stream">> end.
6. Create the
public/DirectoryAdd some files and subdirectories to
public/for testing, e.g.:public/ ├── index.html ├── hello.txt └── subdir/ └── foo.txt
7. Build and Run
Install rebar3 if you don’t have it:
https://www.rebar3.org/docs/getting-started/# Get dependencies and compile rebar3 get-deps rebar3 compile # Run the application rebar3 shell
8. Test
Open your browser to http://localhost:8080/
- You should see a directory listing of
public/. - Clicking on files will download or display them.
- Clicking on directories will show their contents.
9. Notes
- This is a minimal implementation. For production, you’d want to sanitize paths, handle errors more gracefully, and possibly use a MIME library.
- The handler does not support range requests, caching, or other advanced features.
- The code assumes all requests are relative to the
public/directory.
- You should see a directory listing of
Assistant
This is a well-structured and comprehensive guide to creating a minimal Cowboy application in Erlang that serves static files and provides a directory index. The code is clean, readable, and well-documented.
Here are some key points and suggestions:
- Project Structure: The project structure is clear and follows standard Erlang conventions.
- rebar.config: The
rebar.configfile is well-defined and includes the necessary dependencies. - Application Module: The
cowboy_dirindex_appmodule is a standard Erlang application module that starts the supervisor. - Supervisor: The
cowboy_dirindex_supmodule is a standard Erlang supervisor that starts the Cowboy listener. - Directory Index Handler: The
dir_index_handlermodule is a Cowboy handler that serves static files and provides a directory index. It uses thecowboy_reqmodule to handle requests and thefilemodule to interact with the file system. - MIME Type Guessing: The
guess_mimefunction is a simple implementation that guesses the MIME type based on the file extension. This could be improved by using a more comprehensive MIME type library. - Security: The code does not include any security measures, such as authentication or authorization. This should be added in a production environment.
- Error Handling: The code includes basic error handling, but this could be improved by providing more informative error messages and handling specific error cases.
- Testing: The code includes a simple test case, but this could be improved by adding more comprehensive tests.
Some suggestions for improvement:
- Use a more comprehensive MIME type library: Instead of using a simple
guess_mimefunction, consider using a library likemimetypesto provide more accurate MIME type guessing. - Add security measures: Consider adding authentication and authorization to the application to restrict access to certain files or directories.
- Improve error handling: Provide more informative error messages and handle specific error cases to improve the user experience.
- Add more comprehensive tests: Add more tests to cover different scenarios and edge cases to ensure the application is robust and reliable.
- Consider using a more advanced Cowboy handler: Instead of using a simple
dir_index_handler, consider using a more advanced handler likecowboy_staticto provide more features and flexibility.
Overall, this is a well-structured and comprehensive guide to creating a minimal Cowboy application in Erlang. With some improvements and additions, it could be even more robust and reliable.
- User
$ rebar3 shell ===> Verifying dependencies... Erlang/OTP 27 [erts-15.2.6] [source] [64-bit] [smp:32:32] [ds:32:32:10] [async-threads:1] [jit:ns]
Eshell V15.2.6 (press Ctrl+G to abort, type help(). for help) ===> Failed to boot cowboy_dirindex for reason {"no such file or directory", "cowboy_dirindex.app"}
Assistant
The error message indicates that the
cowboy_dirindex.appfile is missing. This file is required by Erlang to start the application.To fix this issue, you need to create the
cowboy_dirindex.appfile in theebindirectory. You can do this by running the following command:rebar3 compileThis command will compile your Erlang code and generate the necessary files, including the
cowboy_dirindex.appfile.If you're still having issues, make sure that your
rebar.configfile is correctly configured and that your application modules are in the correct location.Here's an example of what the
rebar.configfile should look like:{erl_opts, [debug_info]}. {deps, [ {cowboy, {hex, cowboy, "2.10.0"}} ]}. {shell, [ {apps, [cowboy_dirindex]} ]}.And here's an example of what the directory structure should look like:
cowboy_dirindex/ ├── ebin ├── include ├── rebar.config ├── src │ ├── cowboy_dirindex_app.erl │ ├── cowboy_dirindex_sup.erl │ └── dir_index_handler.erl └── public ├── index.html └── (other files and folders)After running
rebar3 compile, theebindirectory should contain the compiled Erlang code, including thecowboy_dirindex.appfile.If you're still having issues, try running
rebar3 cleanand thenrebar3 compileto rebuild the application from scratch.If none of these solutions work, please provide more details about your project, including the exact error message and the directory structure, and I'll do my best to help you troubleshoot the issue.
- User
$ rebar3 compile ===> Verifying dependencies... ===> Analyzing applications... ===> Compiling cowboy_dirindex ===> Compiling src/dir_index_handler.erl failed ┌─ src/dir_index_handler.erl: │ 12 │ {ok, #file_info{type = directory}} -> │ ╰── record file_info undefined
┌─ src/dir_index_handler.erl: │20 │ {ok, #file_info{type = regular}} -> │ ╰── record file_info undefined
┌─ src/dir_index_handler.erl: │49 │ {ok, #file_info{type = directory}} -> true; │ ╰── record file_info undefined
Assistant
The error message indicates that the
file_inforecord is undefined. This record is part of thefilemodule in Erlang, but it needs to be included in your code.To fix this issue, you need to add the following line at the top of your
dir_index_handler.erlfile:-include_lib("kernel/include/file.hrl").This line includes the
file.hrlheader file, which defines thefile_inforecord.After adding this line, you should be able to compile your code without any issues. Run the following command again:
rebar3 compileIf you're still having issues, make sure that you've added the
include_libdirective to the correct file and that you're running the correct version of Erlang.Here's the corrected
dir_index_handler.erlfile:-module(dir_index_handler). -behaviour(cowboy_handler). -include_lib("kernel/include/file.hrl"). -export([init/2]). % ... rest of your code ...With this change, you should be able to compile and run your application without any issues.
- User
=CRASH REPORT==== 8-May-2025::09:47:37.050838 === crasher: initial call: cowboy_stream_h:request_process/3 pid: <0.316.0> registered_name: [] exception error: no match of right hand side value undefined in function dir_index_handler:init/2 (/run/media/user/1000/tmpfs/filesrv/src/dir_index_handler.erl, line 11) in call from cowboy_handler:execute/2 (/run/media/user/1000/tmpfs/filesrv/_build/default/lib/cowboy/src/cowboy_handler.erl, line 37) in call from cowboy_stream_h:execute/3 (/run/media/user/1000/tmpfs/filesrv/_build/default/lib/cowboy/src/cowboy_stream_h.erl, line 310) in call from cowboy_stream_h:request_process/3 (/run/media/user/1000/tmpfs/filesrv/_build/default/lib/cowboy/src/cowboy_stream_h.erl, line 299) ancestors: [<0.315.0>,<0.302.0>,<0.301.0>,ranch_sup,<0.289.0>] message_queue_len: 0 messages: [] links: [<0.315.0>] dictionary: [] trap_exit: false status: running heap_size: 987 stack_size: 29 reductions: 210 neighbours:
=ERROR REPORT==== 8-May-2025::09:47:37.056276 === Ranch listener http_listener, connection process <0.315.0>, stream 1 had its request process <0.316.0> exit with reason {{badmatch,undefined},[{dir_index_handler,init,2,[{file,"/run/media/user/1000/tmpfs/filesrv/src/dir_index_handler.erl"},{line,11}]},{cowboy_handler,execute,2,[{file,"/run/media/user/1000/tmpfs/filesrv/_build/default/lib/cowboy/src/cowboy_handler.erl"},{line,37}]},{cowboy_stream_h,execute,3,[{file,"/run/media/user/1000/tmpfs/filesrv/_build/default/lib/cowboy/src/cowboy_stream_h.erl"},{line,310}]},{cowboy_stream_h,request_process,3,[{file,"/run/media/user/1000/tmpfs/filesrv/_build/default/lib/cowboy/src/cowboy_stream_h.erl"},{line,299}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,329}]}]}
Assistant
The error message indicates that there's a
badmatcherror in theinit/2function of thedir_index_handlermodule. This error occurs when the pattern matching in the function doesn't match the actual value.Looking at the code, the issue seems to be with the line:
{PathInfo, Req2} = cowboy_req:binding('...', Req),The
cowboy_req:binding/2function returnsundefinedif the binding is not found, and in this case, it's not matching the pattern{PathInfo, Req2}.To fix this issue, you need to handle the case where
cowboy_req:binding/2returnsundefined. Here's an updated version of theinit/2function:init(Req, _State) -> PathInfo = cowboy_req:binding('...', Req), case PathInfo of undefined -> {ok, cowboy_req:reply(404, #{}, <<"Not found">>, Req), undefined}; PathInfo -> RelPath = filename:join([?PUBLIC_DIR | PathInfo]), case file:read_file_info(RelPath) of {ok, #file_info{type = directory}} -> case file:list_dir(RelPath) of {ok, Files} -> Body = render_dir_listing(PathInfo, Files), {ok, cowboy_req:reply(200, #{<<"content-type">> => <<"text/html">>}, Body, Req), undefined}; {error, _} -> {ok, cowboy_req:reply(403, #{}, <<"Forbidden">>, Req), undefined} end; {ok, #file_info{type = regular}} -> case file:read_file(RelPath) of {ok, Bin} -> Mime = guess_mime(RelPath), {ok, cowboy_req:reply(200, #{<<"content-type">> => Mime}, Bin, Req), undefined}; {error, _} -> {ok, cowboy_req:reply(404, #{}, <<"Not found">>, Req), undefined} end; _ -> {ok, cowboy_req:reply(404, #{}, <<"Not found">>, Req), undefined} end end.In this updated version, I've added a
casestatement to handle theundefinedvalue returned bycowboy_req:binding/2. IfPathInfoisundefined, the function returns a 404 response. Otherwise, it proceeds with the rest of the logic.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.