Serving Static Files
warp provides easy-to-use filters for serving static files and directories from your filesystem. These filters handle details like setting the correct Content-Type, and supporting conditional and range requests automatically.
Serving a Single File
To serve a single, specific file, use the warp::fs::file() filter. It takes a path to the file on disk.
use warp::Filter;
// Create a route that serves the README.md file at the root path.
let readme = warp::get()
.and(warp::path::end())
.and(warp::fs::file("./README.md"));
// To run this:
// warp::serve(readme).run(([127, 0, 0, 1], 3030)).await;
This will serve the README.md file for any GET request to /. The Content-Type header will be automatically set to text/markdown based on the file extension.
Serving a Directory
To serve an entire directory of static assets, use the warp::fs::dir() filter. It takes a base path to the directory.
warp will take the unmatched "tail" of the request path and append it to the base directory path to find the file to serve.
use warp::Filter;
// Create a route that serves files from the './examples/' directory
// for any request starting with '/ex'.
let examples = warp::path("ex").and(warp::fs::dir("./examples/"));
// For example:
// GET /ex/hello.rs -> serves ./examples/hello.rs
// GET /ex/dir/index.html -> serves ./examples/dir/index.html
// To run this:
// warp::serve(examples).run(([127, 0, 0, 1], 3030)).await;
Features of warp::fs::dir():
- Security: It sanitizes the path to prevent directory traversal attacks (e.g., requests with
..are rejected). - Index File: If a request points to a directory, it will automatically look for and serve an
index.htmlfile inside that directory. - Method Handling: It automatically handles
GETandHEADrequests.
Advanced Features
The filesystem filters in warp come with powerful features built-in:
- Conditional Requests: They automatically handle
If-Modified-SinceandIf-Unmodified-Sinceheaders, returning a304 Not Modifiedor412 Precondition Failedresponse when appropriate. - Range Requests: They support the
Rangeheader, allowing clients like video players or download managers to request partial content. This results in a206 Partial Contentresponse.