Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-03-26-experimental· 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-3.3-70b-instruct’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

    Let's break down this Cowboy application step by step, focusing on how it works, why certain decisions were made, and how you can extend or modify it.

    Overview

    This Erlang application uses Cowboy (a lightweight HTTP server) to:

    1. Serve static files from a directory called public/.
    2. Generate a directory index (like Apache's autoindex) when you navigate to a folder.

    Think of it like a simple web server: go to http://localhost:8080/, and you see the contents of public/ as a clickable list. It's perfect for:

    • Prototyping web UIs.
    • Sharing files locally.
    • Learning Cowboy and Erlang.

    Now, let's dissect the code.

    1. Project Structure

    cowboy_dirindex/
    ├── rebar.config       # Project config (dependencies, build settings)
    ├── src/               # Erlang source files
    │   ├── cowboy_dirindex_app.erl # OTP application behavior
    │   ├── cowboy_dirindex_sup.erl # Supervisor (starts Cowboy)
    │   └── dir_index_handler.erl   # The meat: request handler
    └── public/            # Static files served here
    
    • rebar.config: Tells rebar3 (Erlang's build tool) what dependencies we need (Cowboy 2.10.0) and how to run the app.
    • src/: OTP boilerplate (_app.erl, _sup.erl) plus our custom logic in dir_index_handler.erl.
    • public/: Where your website's files live. Try adding index.html, images/, etc.

    2. rebar.config

    {erl_opts, [debug_info]}. % Compiler option: include debug symbols
    
    {deps, [ % Dependencies (fetched from Hex.pm)
        {cowboy, {hex, cowboy, "2.10.0"}} % Cowboy 2.10.0
    ]}.
    
    {shell, [ % When running `rebar3 shell`
        {apps, [cowboy_dirindex]} % Auto-start our app
    ]}.
    
    • erl_opts: Just tells the compiler to include debugging info. Handy for crash dumps.
    • deps: We need Cowboy 2.10.0. Run rebar3 get-deps to download it.
    • {shell, [...]}: When you run rebar3 shell, it starts our cowboy_dirindex app automatically.

    3. Application Module (cowboy_dirindex_app.erl)

    This is OTP boilerplate. Every Erlang application needs:

    -module(cowboy_dirindex_app).
    -behaviour(application). % OTP application behavior
    
    -export([start/2, stop/1]). % Mandatory callbacks
    
    start(_Type, _Args) ->
        cowboy_dirindex_sup:start_link(). % Start the supervisor
    
    stop(_State) ->
        ok. % Cleanup (we don't need any)
    
    • An OTP app must have start/2 and stop/1.
    • start/2 launches the supervisor, which in turn starts Cowboy.
    • stop/1 is called when the app shuts down. Here, we do nothing.

    4. Supervisor (cowboy_dirindex_sup.erl)

    The supervisor's job is to start and monitor our HTTP listener:

    -module(cowboy_dirindex_sup).
    -behaviour(supervisor). % OTP supervisor
    
    -export([start_link/0, init/1]).
    
    start_link() ->
        supervisor:start_link({local, ?MODULE}, ?MODULE, []). % Start self
    
    init([]) ->
        Dispatch = cowboy_router:compile([ % Define routes
            {'_', [ % Catch-all host (any domain/IP)
                {"/[...]", dir_index_handler, []} % All paths -> our handler
            ]}
        ]),
        {ok, _} = cowboy:start_clear(http_listener, [ % Start HTTP server
            {port, 8080} % Listen on port 8080
        ], #{
            env => #{dispatch => Dispatch} % Pass routes to Cowboy
        }),
        {ok, {{one_for_one, 10, 10}, []}}. % Supervisor strategy (don't worry)
    

    Key points:

    1. cowboy_router:compile defines URL routes. Here:

      • {'_'} means "any hostname" (localhost, 127.0.0.1, ...).
      • "/[...]" is Cowboy's way of saying "catch all paths". ... gives us the URL pieces (e.g., /foo/bar becomes ["foo", "bar"]).
      • dir_index_handler is our module that handles every request.
    2. cowboy:start_clear starts the HTTP server:

      • http_listener is just a name.
      • {port, 8080} says "listen on port 8080".
      • env => #{dispatch => Dispatch} links our routes to Cowboy.
    3. The last line ({ok, {{one_for_one, 10, 10}, []}}) is OTP supervisor strategy:

      • If a child crashes, restart it (up to 10 times in 10 seconds). We have no children yet, so [] is empty.

    5. The Magic: dir_index_handler.erl

    This module handles all requests. It decides:

    • If the URL points to a file, serve that file.
    • If it's a directory, generate an HTML index (like ls -l).

    Here's the core logic:

    init(Req, _State) ->
        {PathInfo, Req2} = cowboy_req:binding('...', Req), % Get URL path
        RelPath = filename:join([?PUBLIC_DIR | PathInfo]), % public/foo/bar
        case file:read_file_info(RelPath) of
            {ok, #file_info{type = directory}} -> handle_directory(Req2, PathInfo, RelPath);
            {ok, #file_info{type = regular}}   -> serve_file(Req2, RelPath);
            _                                  -> cowboy_req:reply(404, #{}, <<"Not found">>, Req2)
        end.
    

    Let's break it down:

    1. cowboy_req:binding('...', Req): Extracts the URL path as a list.

      • / → []
      • /foo → ["foo"]
      • /foo/bar → ["foo", "bar"]
    2. filename:join([?PUBLIC_DIR | PathInfo]): Prepends public/ to the path.

      • [] → "public"
      • ["foo"] → "public/foo"
      • ["foo", "bar"] → "public/foo/bar"
    3. file:read_file_info(RelPath): Checks if the path exists and is:

      • A directory: Show directory listing (we'll get to that).
      • A regular file: Serve the file contents.
      • Missing/error: 404.

    Serving a File

    serve_file(Req, RelPath) ->
        case file:read_file(RelPath) of
            {ok, Bin} ->
                Mime = guess_mime(RelPath), % .html -> text/html, .jpg -> image/jpeg, etc.
                cowboy_req:reply(200, #{<<"content-type">> => Mime}, Bin, Req);
            _ ->
                cowboy_req:reply(404, #{}, <<"Not found">>, Req)
        end.
    
    guess_mime(Filename) ->
        case filename:extension(Filename) of
            ".html" -> <<"text/html">>;
            ".txt"  -> <<"text/plain">>;
            ".png"  -> <<"image/png">>;
            _       -> <<"application/octet-stream">> % Default (binary data)
        end.
    
    • file:read_file(RelPath): Slurps the whole file into memory (fine for small files; for huge files, use streams).
    • guess_mime/1: Basic extension → MIME type mapping.
      You can replace this with a library like mime or mimetypes if you need more types.

    Directory Listing (The Fun Part)

    When you hit a directory, we generate HTML:

    handle_directory(Req, PathInfo, RelPath) ->
        case file:list_dir(RelPath) of
            {ok, Files} ->
                Body = render_dir_listing(PathInfo, Files),
                cowboy_req:reply(200, #{<<"content-type">> => <<"text/html">>}, Body, Req);
            {error, _} ->
                cowboy_req:reply(403, #{}, <<"Forbidden">>, Req)
        end.
    
    render_dir_listing(PathInfo, Files) ->
        Path = "/" ++ string:join([unicode:characters_to_list(P) || P <- PathInfo], "/"),
        ParentLink = case PathInfo of
                         [] -> ""; % Top level, no ../
                         _  -> "<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([ParentLink | 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.
    

    Here's what happens:

    1. file:list_dir(RelPath): Gets a list of files/folders in that directory.
    2. We generate HTML:
      • Path is the URL path ("/foo/bar").
      • If not at the root, we add a ../ link.
      • FileLinks are <li><a href="file.txt">file.txt</a></li> or <li><a href="subdir/">subdir/</a></li> (note the trailing / for dirs).
    3. We build a simple <html>...</html> string with the file list.

    Example output for http://localhost:8080/ if public/ has:

    index.html
    hello.txt
    images/
    

    You'll see:

    <html>
      <head><title>Index of /</title></head>
      <body>
        <h1>Index of /</h1>
        <ul>
          <li><a href="index.html">index.html</a></li>
          <li><a href="hello.txt">hello.txt</a></li>
          <li><a href="images/">images/</a></li>
        </ul>
      </body>
    </html>
    

    6. Running It

    1. Install rebar3: https://rebar3.org/docs/getting-started/
    2. Run:
      rebar3 get-deps
      rebar3 compile
      rebar3 shell
      
    3. Open http://localhost:8080/

    Security & Improvements

    • Path Traversal: This code assumes public/ is the root. In real life, sanitize paths to prevent ../../../etc/passwd attacks.
    • MIME Types: Expand guess_mime/1 or use a library.
    • Error Pages: Customize 404/403 pages.
    • Performance: For large files, use cowboy_req:stream_body instead of loading into memory.
    • Caching: Add ETag or Cache-Control headers.

    That's it! This example covers:

    • OTP app/sup structure
    • Cowboy routing
    • Static file serving
    • Dynamic directory listings in Erlang

    Now go play with it, break it, and make it better!

  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 you're seeing:

    ===> Failed to boot cowboy_dirindex for reason {"no such file or directory", "cowboy_dirindex.app"}
    

    means Erlang can't find the application resource file (cowboy_dirindex.app) when trying to start your app.

    Here's why this happens and how to fix it:

    What's an .app file?

    In Erlang, every OTP application needs a .app file (not to be confused with .app.src). This file tells Erlang:

    1. The app's name, version, and description.
    2. Which modules belong to the app.
    3. Dependencies (other apps it needs).

    When you run rebar3 shell, it tries to:

    1. Compile your code.
    2. Generate a cowboy_dirindex.app file (from src/cowboy_dirindex.app.src, if it exists).
    3. Start the app using that .app file.

    The Problem

    By default, rebar3 expects a src/cowboy_dirindex.app.src file. But we didn't create one! We only wrote:

    • cowboy_dirindex_app.erl (the app module)
    • cowboy_dirindex_sup.erl (the supervisor)
    • dir_index_handler.erl (the Cowboy handler)

    Solution 1: Create src/cowboy_dirindex.app.src

    In src/, create a new file called cowboy_dirindex.app.src (note the .src extension):

    {application, cowboy_dirindex,
     [
      {description, "Cowboy Directory Index Server"},
      {vsn, "1.0.0"},
      {modules, [
        cowboy_dirindex_app,
        cowboy_dirindex_sup,
        dir_index_handler
      ]},
      {registered, [cowboy_dirindex_sup]},
      {applications, [
        kernel,
        stdlib,
        cowboy % <--- Our dependency
      ]},
      {mod, {cowboy_dirindex_app, []}} % Our app callback module
     ]
    }.
    

    Let's break it down:

    • {application, cowboy_dirindex, [...]}: Defines our app.
    • {description, "..."}: Human-readable description.
    • {vsn, "1.0.0"}: Version number.
    • {modules, [...]}: Lists all our Erlang modules. rebar3 will auto-generate .beam files for these.
    • {registered, [...]}: Names of registered processes (our supervisor).
    • {applications, [...]}: Apps our app depends on. kernel and stdlib are always required; we add cowboy since we use it.
    • {mod, {cowboy_dirindex_app, []}}: Tells OTP that cowboy_dirindex_app:start/2 is our entry point.

    Now, re-run:

    rebar3 clean
    rebar3 compile
    rebar3 shell
    

    It should work! You should see Cowboy starting, and you can visit http://localhost:8080/.

    Solution 2: Use relx (Optional but Recommended)

    If you plan to deploy this app, you'll eventually need a release. rebar3 has built-in support via relx. Here's a quick setup:

    1. Add relx config to rebar.config:
    {relx, [
        {release, {cowboy_dirindex, "1.0.0"}, [cowboy_dirindex]},
        {dev_mode, true},
        {include_erts, false},
        {extended_start_script, true}
    ]}.
    
    {profiles, [
        {prod, [
            {relx, [
                {dev_mode, false},
                {include_erts, true}
            ]}
        ]}
    ]}.
    
    1. Still missing cowboy_dirindex.app.src? Create it as above.

    2. Now you can:

      • rebar3 shell (same as before, but more correct).
      • rebar3 release (builds a standalone tarball in _build/default/rel/).
      • rebar3 as prod release (production build, includes Erlang VM).

    Why This Fixes the Problem

    • cowboy_dirindex.app.src tells rebar3 (actually, rebar3 appgen) to generate cowboy_dirindex.app during compilation.
    • That .app file is placed in _build/default/lib/cowboy_dirindex/ebin/.
    • When you run rebar3 shell, it loads this .app file and starts your app properly.

    Without it, Erlang complains: "I don't know what cowboy_dirindex is or how to start it."

    Now you're all set! Happy Cowboy-ing!

    Troubleshooting Tips

    • If you still see errors, try rebar3 clean before recompiling.
    • Ensure your src/ folder only has .erl files and the one .app.src.
    • Check rebar3 compile output for warnings (e.g., missing modules in .app.src).

    Run this, and you should see Cowboy up and serving files:

    $ rebar3 shell
    ===> Starting relx build process ...
    ===> Resolving OTP Applications from directories:
              /path/to/cowboy_dirindex/_build/default/lib
              /path/to/rebar3/lib
              /usr/lib/erlang/27.0/lib
    ===> Resolved cowboy_dirindex-1.0.0
    ===> Including Erts from /usr/lib/erlang/27.0
    ===> release successfully created!
    Exec: /path/to/cowboy_dirindex/_build/default/rel/cowboy_dirindex/bin/cowboy_dirindex console
    Root: /path/to/cowboy_dirindex/_build/default/rel/cowboy_dirindex
    Erlang/OTP 27 [erts-15.2.6] ...
    Eshell V15.2.6 ...
    (cowboy_dirindex@localhost)1> 
    

    Visit http://localhost:8080/, and enjoy your directory index!

  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:

    record file_info undefined
    

    means Erlang doesn't know what the #file_info record is.

    Why This Happens

    In Erlang, records are compile-time constructs. When you write:

    #file_info{type = directory}
    

    The compiler needs to know the definition of file_info.

    The file_info record is defined in kernel/include/file.hrl. This header file is part of Erlang's standard library (stdlib), but you need to explicitly include it in your .erl files that use #file_info{}.

    The Fix

    In src/dir_index_handler.erl, add this line at the top, right after -module(dir_index_handler).:

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

    Here's how the first few lines should look:

    -module(dir_index_handler).
    -behaviour(cowboy_handler).
    
    -include_lib("kernel/include/file.hrl"). % <--- ADD THIS LINE
    
    -export([init/2]).
    
    -define(PUBLIC_DIR, "public").
    ...
    

    What does -include_lib do?

    • -include("myfile.hrl"). would look for myfile.hrl relative to the current directory (e.g., src/myfile.hrl).
    • -include_lib("kernel/include/file.hrl"). tells Erlang:
      1. Find the kernel application (part of OTP).
      2. Look in its include/ directory.
      3. Include file.hrl from there.

    kernel/include/file.hrl defines:

    -record(file_info,
            {size   :: non_neg_integer(), % Size of file in bytes.
             type   :: file:file_type(),  % Atom: 'device', 'directory', 'regular', 'other', or 'symlink' (OTP 26+)
             access :: file:access(),     % 'read', 'write', 'read_write', or 'none'
             atime  :: file:date_time(),  % Last access, {{Year,Month,Day},{Hour,Min,Sec}}
             mtime  :: file:date_time(),  % Last modify
             ctime  :: file:date_time(),  % Last change (UNIX: last metadata change, Windows: creation time)
             mode   :: non_neg_integer(), % File permissions (Unix: mode bits, Win: ignored)
             links  :: non_neg_integer(), % Number of links to the file (1 if the OS does not support links)
             major_device :: non_neg_integer(), % Identifies the file system (Unix: major device number)
             minor_device :: non_neg_integer(), % Identifies the file in the file system (Unix: minor device number)
             inode    :: non_neg_integer(), % The file number (Unix) / The indexNode number (Win32)
             uid      :: non_neg_integer(), % User id of owner (Unix) / 0 (Win32)
             gid      :: non_neg_integer()  % Group id of owner (Unix) / 0 (Win32)
            }).
    

    Without this include, Erlang sees #file_info{...} and says: "I have no idea what fields file_info has!"

    Now Recompile

    Run:

    rebar3 clean
    rebar3 compile
    rebar3 shell
    

    It should compile without errors. If you still see issues:

    1. Ensure the line is exactly -include_lib("kernel/include/file.hrl"). (no typos).
    2. Try rm -rf _build/ (nuke the build dir) and recompile.

    Aside: Other Includes You Might Need

    • For #inet (socket options): -include_lib("kernel/include/inet.hrl").
    • For #mimetypes (if using mimetypes app): -include_lib("mimetypes/include/mimetypes.hrl").

    But for file_info, kernel/include/file.hrl is all you need.

    Full dir_index_handler.erl Header Should Look Like This

    -module(dir_index_handler).
    -behaviour(cowboy_handler).
    
    -include_lib("kernel/include/file.hrl"). % <-- THIS IS THE IMPORTANT LINE
    
    -export([init/2]).
    
    -define(PUBLIC_DIR, "public").
    
    init(Req, _State) ->
        ...
    

    Happy compiling!

    Now, when you visit http://localhost:8080/, you should see your public/ directory listing.

    Next Steps

    • Want better MIME types? Replace guess_mime/1 with a library like mimetypes.
    • Need security? Sanitize paths to prevent ../../../etc/passwd hacks.
    • Curious about performance? Profile with eprof or fprof.

    Let me know if rebar3 shell now boots your Cowboy server successfully!

  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 crash report is telling you exactly what's wrong:

    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)
    

    Let's break it down:

    The Problematic Line

    In src/dir_index_handler.erl, line 11 is crashing. Here's what's likely there:

    {PathInfo, Req2} = cowboy_req:binding('...', Req),
    

    The Issue: undefined

    cowboy_req:binding('...', Req) is returning undefined.

    In Erlang, this line:

    {PathInfo, Req2} = cowboy_req:binding('...', Req),
    

    expects a tuple {Value, NewReq}. But if cowboy_req:binding/2 returns undefined, you're essentially doing:

    {PathInfo, Req2} = undefined,
    

    Which is a badmatch error. Erlang says: "I can't pattern-match undefined into a {X, Y} tuple!"

    Why undefined?

    In Cowboy 2.x, cowboy_req:binding/2 returns undefined when:

    1. The binding doesn't exist in the route.
    2. Or, more likely here: '...' is not a valid binding name.

    The Fix: Use cowboy_req:path_info/1

    For catching all remaining path segments, Cowboy provides cowboy_req:path_info/1, not binding('...', Req).

    Replace line 11 with:

    {PathInfo, Req2} = {cowboy_req:path_info(Req), Req},
    

    Or, even simpler:

    PathInfo = cowboy_req:path_info(Req),
    

    Why This Works

    • cowboy_req:path_info(Req) returns the remaining path segments as a list.

      • / → []
      • /foo → ["foo"]
      • /foo/bar → ["foo", "bar"]
    • It never returns undefined. If there's no path, it's an empty list [].

    Updated init/2 Function

    Here's how init/2 should look:

    init(Req, _State) ->
        PathInfo = cowboy_req:path_info(Req), % <--- CHANGED HERE
        RelPath = filename:join([?PUBLIC_DIR | PathInfo]),
        case file:read_file_info(RelPath) of
            {ok, #file_info{type = directory}} ->
                handle_directory(Req, PathInfo, RelPath);
            {ok, #file_info{type = regular}} ->
                serve_file(Req, RelPath);
            _ ->
                cowboy_req:reply(404, #{}, <<"Not found">>, Req)
        end.
    

    Recap

    1. cowboy_req:binding('...', Req) is wrong. '...' isn't a magic variable in Cowboy 2.x.
    2. cowboy_req:path_info(Req) is the correct way to get the full path segments.

    Now:

    rebar3 clean
    rebar3 compile
    rebar3 shell
    

    Visit http://localhost:8080/. It should work!

    Troubleshooting Tips

    • Still crashing? Check the error message line number again.
    • Ensure you saved the file after editing.
    • If weirdness persists, rm -rf _build/ and recompile.

    Full Correct dir_index,handler.erl

    -module(dir_index_handler).
    -behaviour(cowboy_handler).
    
    -include_lib("kernel/include/file.hrl").
    
    -export([init/2]).
    
    -define(PUBLIC_DIR, "public").
    
    init(Req, _State) ->
        PathInfo = cowboy_req:path_info(Req),
        RelPath = filename:join([?PUBLIC_DIR | PathInfo]),
        case file:read_file_info(RelPath) of
            {ok, #file_info{type = directory}} ->
                handle_directory(Req, PathInfo, RelPath);
            {ok, #file_info{type = regular}} ->
                serve_file(Req, RelPath);
            _ ->
                cowboy_req:reply(404, #{}, <<"Not found">>, Req)
        end.
    
    handle_directory(Req, PathInfo, RelPath) ->
        case file:list_dir(RelPath) of
            {ok, Files} ->
                Body = render_dir_listing(PathInfo, Files),
                cowboy_req:reply(200, #{<<"content-type">> => <<"text/html">>}, Body, Req);
            {error, _} ->
                cowboy_req:reply(403, #{}, <<"Forbidden">>, Req)
        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.
    
    serve_file(Req, RelPath) ->
        case file:read_file(RelPath) of
            {ok, Bin} ->
                Mime = guess_mime(RelPath),
                cowboy_req:reply(200, #{<<"content-type">> => Mime}, Bin, Req);
            _ ->
                cowboy_req:reply(404, #{}, <<"Not found">>, Req)
        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.
    

    Now you're serving files and dirs like a pro!

    Happy Erlang-ing!

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