Skip to content
TheChatArchiveThe Chat Archive
Metallama-3.3-70b-instruct· MetaHugging Face LMArena Human Preference 140K

Absolutely! Here’s a minimal, complete Cowboy application in Erlang that serves static…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. 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/ Directory

    Add 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.
  2. Meta 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:

    1. Project Structure: The project structure is clear and follows standard Erlang conventions.
    2. rebar.config: The rebar.config file is well-defined and includes the necessary dependencies.
    3. Application Module: The cowboy_dirindex_app module is a standard Erlang application module that starts the supervisor.
    4. Supervisor: The cowboy_dirindex_sup module is a standard Erlang supervisor that starts the Cowboy listener.
    5. Directory Index Handler: The dir_index_handler module is a Cowboy handler that serves static files and provides a directory index. It uses the cowboy_req module to handle requests and the file module to interact with the file system.
    6. MIME Type Guessing: The guess_mime function 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.
    7. Security: The code does not include any security measures, such as authentication or authorization. This should be added in a production environment.
    8. Error Handling: The code includes basic error handling, but this could be improved by providing more informative error messages and handling specific error cases.
    9. Testing: The code includes a simple test case, but this could be improved by adding more comprehensive tests.

    Some suggestions for improvement:

    1. Use a more comprehensive MIME type library: Instead of using a simple guess_mime function, consider using a library like mimetypes to provide more accurate MIME type guessing.
    2. Add security measures: Consider adding authentication and authorization to the application to restrict access to certain files or directories.
    3. Improve error handling: Provide more informative error messages and handle specific error cases to improve the user experience.
    4. Add more comprehensive tests: Add more tests to cover different scenarios and edge cases to ensure the application is robust and reliable.
    5. Consider using a more advanced Cowboy handler: Instead of using a simple dir_index_handler, consider using a more advanced handler like cowboy_static to 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.

  3. 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"}

  4. Meta Assistant

    The error message indicates that the cowboy_dirindex.app file is missing. This file is required by Erlang to start the application.

    To fix this issue, you need to create the cowboy_dirindex.app file in the ebin directory. You can do this by running the following command:

    rebar3 compile
    

    This command will compile your Erlang code and generate the necessary files, including the cowboy_dirindex.app file.

    If you're still having issues, make sure that your rebar.config file is correctly configured and that your application modules are in the correct location.

    Here's an example of what the rebar.config file 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, the ebin directory should contain the compiled Erlang code, including the cowboy_dirindex.app file.

    If you're still having issues, try running rebar3 clean and then rebar3 compile to 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.

  5. 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

  6. Meta Assistant

    The error message indicates that the file_info record is undefined. This record is part of the file module 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.erl file:

    -include_lib("kernel/include/file.hrl").
    

    This line includes the file.hrl header file, which defines the file_info record.

    After adding this line, you should be able to compile your code without any issues. Run the following command again:

    rebar3 compile
    

    If you're still having issues, make sure that you've added the include_lib directive to the correct file and that you're running the correct version of Erlang.

    Here's the corrected dir_index_handler.erl file:

    -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.

  7. 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}]}]}

  8. Meta Assistant

    The error message indicates that there's a badmatch error in the init/2 function of the dir_index_handler module. 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/2 function returns undefined if 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/2 returns undefined. Here's an updated version of the init/2 function:

    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 case statement to handle the undefined value returned by cowboy_req:binding/2. If PathInfo is undefined, the function returns a 404 response. Otherwise, it proceeds with the rest of the logic.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.