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
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:
- Serve static files from a directory called
public/. - 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 ofpublic/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 hererebar.config: Tellsrebar3(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 indir_index_handler.erl.public/: Where your website's files live. Try addingindex.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. Runrebar3 get-depsto download it.{shell, [...]}: When you runrebar3 shell, it starts ourcowboy_dirindexapp 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/2andstop/1. start/2launches the supervisor, which in turn starts Cowboy.stop/1is 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:
-
cowboy_router:compiledefines 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/barbecomes["foo", "bar"]).dir_index_handleris our module that handles every request.
-
cowboy:start_clearstarts the HTTP server:http_listeneris just a name.{port, 8080}says "listen on port 8080".env => #{dispatch => Dispatch}links our routes to Cowboy.
-
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.
- If a child crashes, restart it (up to 10 times in 10 seconds). We have no children yet, so
5. The Magic:
dir_index_handler.erlThis 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:
-
cowboy_req:binding('...', Req): Extracts the URL path as a list./→[]/foo→["foo"]/foo/bar→["foo", "bar"]
-
filename:join([?PUBLIC_DIR | PathInfo]): Prependspublic/to the path.[]→"public"["foo"]→"public/foo"["foo", "bar"]→"public/foo/bar"
-
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 likemimeormimetypesif 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:
file:list_dir(RelPath): Gets a list of files/folders in that directory.- We generate HTML:
Pathis the URL path ("/foo/bar").- If not at the root, we add a
../link. FileLinksare<li><a href="file.txt">file.txt</a></li>or<li><a href="subdir/">subdir/</a></li>(note the trailing/for dirs).
- We build a simple
<html>...</html>string with the file list.
Example output for
http://localhost:8080/ifpublic/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
- Install
rebar3: https://rebar3.org/docs/getting-started/ - Run:
rebar3 get-deps rebar3 compile rebar3 shell - Open http://localhost:8080/
Security & Improvements
- Path Traversal: This code assumes
public/is the root. In real life, sanitize paths to prevent../../../etc/passwdattacks. - MIME Types: Expand
guess_mime/1or use a library. - Error Pages: Customize 404/403 pages.
- Performance: For large files, use
cowboy_req:stream_bodyinstead of loading into memory. - Caching: Add
ETagorCache-Controlheaders.
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!
- Serve static files from a directory called
- 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 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
.appfile?In Erlang, every OTP application needs a
.appfile (not to be confused with.app.src). This file tells Erlang:- The app's name, version, and description.
- Which modules belong to the app.
- Dependencies (other apps it needs).
When you run
rebar3 shell, it tries to:- Compile your code.
- Generate a
cowboy_dirindex.appfile (fromsrc/cowboy_dirindex.app.src, if it exists). - Start the app using that
.appfile.
The Problem
By default,
rebar3expects asrc/cowboy_dirindex.app.srcfile. 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.srcIn
src/, create a new file calledcowboy_dirindex.app.src(note the.srcextension):{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.rebar3will auto-generate.beamfiles for these.{registered, [...]}: Names of registered processes (our supervisor).{applications, [...]}: Apps our app depends on.kernelandstdlibare always required; we addcowboysince we use it.{mod, {cowboy_dirindex_app, []}}: Tells OTP thatcowboy_dirindex_app:start/2is our entry point.
Now, re-run:
rebar3 clean rebar3 compile rebar3 shellIt 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.
rebar3has built-in support viarelx. Here's a quick setup:- Add
relxconfig torebar.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} ]} ]} ]}.-
Still missing
cowboy_dirindex.app.src? Create it as above. -
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.srctellsrebar3(actually,rebar3 appgen) to generatecowboy_dirindex.appduring compilation.- That
.appfile is placed in_build/default/lib/cowboy_dirindex/ebin/. - When you run
rebar3 shell, it loads this.appfile and starts your app properly.
Without it, Erlang complains: "I don't know what
cowboy_dirindexis or how to start it."Now you're all set! Happy Cowboy-ing!
Troubleshooting Tips
- If you still see errors, try
rebar3 cleanbefore recompiling. - Ensure your
src/folder only has.erlfiles and the one.app.src. - Check
rebar3 compileoutput 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!
- 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:
record file_info undefinedmeans Erlang doesn't know what the
#file_inforecord 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_inforecord is defined inkernel/include/file.hrl. This header file is part of Erlang's standard library (stdlib), but you need to explicitly include it in your.erlfiles 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_libdo?-include("myfile.hrl").would look formyfile.hrlrelative to the current directory (e.g.,src/myfile.hrl).-include_lib("kernel/include/file.hrl").tells Erlang:- Find the
kernelapplication (part of OTP). - Look in its
include/directory. - Include
file.hrlfrom there.
- Find the
kernel/include/file.hrldefines:-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 fieldsfile_infohas!"Now Recompile
Run:
rebar3 clean rebar3 compile rebar3 shellIt should compile without errors. If you still see issues:
- Ensure the line is exactly
-include_lib("kernel/include/file.hrl").(no typos). - 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 usingmimetypesapp):-include_lib("mimetypes/include/mimetypes.hrl").
But for
file_info,kernel/include/file.hrlis all you need.Full
dir_index_handler.erlHeader 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/1with a library likemimetypes. - Need security? Sanitize paths to prevent
../../../etc/passwdhacks. - Curious about performance? Profile with
eproforfprof.
Let me know if
rebar3 shellnow boots your Cowboy server successfully!- 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 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:
undefinedcowboy_req:binding('...', Req)is returningundefined.In Erlang, this line:
{PathInfo, Req2} = cowboy_req:binding('...', Req),expects a tuple
{Value, NewReq}. But ifcowboy_req:binding/2returnsundefined, you're essentially doing:{PathInfo, Req2} = undefined,Which is a
badmatcherror. Erlang says: "I can't pattern-matchundefinedinto a{X, Y}tuple!"Why
undefined?In Cowboy 2.x,
cowboy_req:binding/2returnsundefinedwhen:- The binding doesn't exist in the route.
- Or, more likely here:
'...'is not a valid binding name.
The Fix: Use
cowboy_req:path_info/1For catching all remaining path segments, Cowboy provides
cowboy_req:path_info/1, notbinding('...', 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/2FunctionHere's how
init/2should 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
cowboy_req:binding('...', Req)is wrong.'...'isn't a magic variable in Cowboy 2.x.cowboy_req:path_info(Req)is the correct way to get the full path segments.
Now:
rebar3 clean rebar3 compile rebar3 shellVisit 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!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.