Serve static files
Serve a directory beside the app's routes with tower-http ServeDir as a pre-dispatch layer.
A directory of files and the app's own routes answer from one port. ServeDir is a tower service rather than a layer, so it enters the pre-dispatch stage through tower::layer::layer_fn, with the rest of the stage as its fallback.
The recipe builds on examples/17-http-pre-dispatch. It compiled and ran on port 0 against tower-http 0.7.1 (feature fs) and tower 0.5.3.
tower = "0.5"
tower-http = { version = "0.7", features = ["fs"] }The code
use std::path::PathBuf;
use tower::layer::layer_fn;
use tower_http::services::ServeDir;
use ulo::{App, AppBuilder, Module, ModuleDef, ModuleIdentity, controller, handlers, module};
use ulo_http::PreDispatch;
pub struct StaticModule {
dir: PathBuf,
}
impl StaticModule {
pub fn new(dir: impl Into<PathBuf>) -> Self {
StaticModule { dir: dir.into() }
}
}
impl Module for StaticModule {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
let dir = self.dir.clone();
m.meta::<PreDispatch>().layer(layer_fn(move |inner| ServeDir::new(&dir).call_fallback_on_method_not_allowed(true).fallback(inner)));
}
}
#[controller]
pub struct PagesController;
#[handlers]
impl PagesController {
#[ulo_http::get("/")]
fn index(&self) -> &'static str {
"the app's own route"
}
#[ulo_http::post("/api/orders")]
fn create(&self) -> &'static str {
"created"
}
}
#[module(imports = [StaticModule::new("public")], controllers = [PagesController])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}What each seam does
layer_fn(|inner| ServeDir::new(&dir).fallback(inner)) builds a Layer from a closure. The stage calls the closure once for each route stack, with inner set to ulo_http::Service: the rest of the stage, then routing and dispatch. ServeDir answers a request when a file matches the path and calls inner when none does, so / and /api/orders reach the controller.
The layer is unscoped, so it also sees paths no route matches. With public/hello.txt and public/docs/index.html on disk, the observed answers were:
| Request | Answer |
|---|---|
GET /hello.txt | 200, content-type: text/plain, content-length: 16, plus accept-ranges, last-modified and etag headers |
GET /docs/ | 200, content-type: text/html, the body of public/docs/index.html |
GET / | 200, the app's own route |
POST /api/orders | 200, created |
GET /nope | 404, the framework's problem document, no route matches this path |
POST /hello.txt | 404, the same document |
call_fallback_on_method_not_allowed(true) lets a request whose method is not GET or HEAD reach inner. The POST /hello.txt row shows what that costs: a file path is not a route, so the stage answers 404 where ServeDir alone would answer 405.
Failure modes
A ServeDir passed to .layer(..) does not compile. PreDispatch::layer takes a tower::Layer<ulo_http::Service> and ServeDir is a service. The compiler names the missing bound:
error[E0277]: the trait bound `ServeDir: Layer<ulo_http::Service>` is not satisfied
= note: required by a bound in `ulo_http::PreDispatch::<T>::layer`layer_fn is the adapter from |inner| service_around(inner) to a Layer.
Without call_fallback_on_method_not_allowed(true), every POST route answers 405. Run without the option, POST /api/orders answered 405 Method Not Allowed with allow: GET,HEAD and the handler never ran. A PUT to a path no route matches did the same. The 405 is a response the layer built, and the pre-dispatch stage hands such a response on as it is, so error handlers never see it.
A file shadows a route. The layer runs first. With public/index.html present, GET / answered the file (content-type: text/html) and the #[ulo_http::get("/")] handler did not run.
The directory resolves against the working directory. ServeDir::new("public") is relative. Started from a directory without public/, GET /hello.txt answered 404 and GET / still reached the route. Give a deployed app an absolute path from configuration.
A traversal never reaches the layer. curl --path-as-is http://host/../Cargo.toml answered 400 with the path holds a . or .. segment, from the server before the stage.
Reference
- Middleware:
PreDispatch,layer,layer_for, and what a layer's own response skips. - Modules:
ModuleandModuleDef, the hand-written form that carriesm.meta::<PreDispatch>().