Static Files
Mount a directory with Runcobo::StaticFiles. It's an HTTP::Handler, so you add it to the server's handler list, in front of the router:
crystal
require "./app"
Runcobo.start(handlers: [
Runcobo::LogHandler.new,
Runcobo::ErrorHandler.new,
Runcobo::StaticFiles.new("/assets", directory: "public", cache_control: "public, max-age=31536000, immutable"),
Runcobo::RouteHandler.new,
Runcobo::RouteNotFoundHandler.new,
] of HTTP::Handler)Now GET /assets/css/app.css serves public/css/app.css.
| Argument | Description |
|---|---|
prefix | URL path to mount at, starting with /. Use "/" to serve from the root. |
directory: | The directory to serve, relative to the working directory or absolute |
cache_control: | Optional Cache-Control value for successful file responses |
Behavior
- Only
GETandHEADare allowed under the prefix; other methods get405with anAllow: GET, HEADheader. - Requests outside the prefix, and files that don't exist, are passed to the next handler — so a missing asset ends in your normal
404. - Directory listings are disabled.
ETag/Last-Modifiedconditional requests andRangerequests are supported.- Precompressed
.gzsiblings are served to clients that accept them.
Safety
Paths are resolved strictly inside the directory. .. segments, encoded traversal (%2e%2e), backslashes, NUL bytes, and symbolic links pointing outside the directory are all treated as "not found".
TIP
Mounting at a dedicated prefix such as /assets keeps static files from shadowing your routes and makes long cache lifetimes safe. Fingerprint file names (e.g. app.3f9a2c.css) when you use immutable.