Struct tower_http::services::fs::ServeDir
source · pub struct ServeDir<F = DefaultServeDirFallback> { /* private fields */ }
fs
only.Expand description
Service that serves files from a given directory and all its sub directories.
The Content-Type
will be guessed from the file extension.
An empty response with status 404 Not Found
will be returned if:
- The file doesn’t exist
- Any segment of the path contains
..
- Any segment of the path contains a backslash
- On unix, any segment of the path referenced as directory is actually an
existing file (
/file.html/something
) - We don’t have necessary permissions to read the file
Example
use tower_http::services::ServeDir;
// This will serve files in the "assets" directory and
// its subdirectories
let service = ServeDir::new("assets");
// Run our service using `hyper`
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
hyper::Server::bind(&addr)
.serve(tower::make::Shared::new(service))
.await
.expect("server error");
Implementations§
source§impl<F> ServeDir<F>
impl<F> ServeDir<F>
sourcepub fn append_index_html_on_directories(self, append: bool) -> Self
pub fn append_index_html_on_directories(self, append: bool) -> Self
If the requested path is a directory append index.html
.
This is useful for static sites.
Defaults to true
.
sourcepub fn with_buf_chunk_size(self, chunk_size: usize) -> Self
pub fn with_buf_chunk_size(self, chunk_size: usize) -> Self
Set a specific read buffer chunk size.
The default capacity is 64kb.
sourcepub fn precompressed_gzip(self) -> Self
pub fn precompressed_gzip(self) -> Self
Informs the service that it should also look for a precompressed gzip version of any file in the directory.
Assuming the dir
directory is being served and dir/foo.txt
is requested,
a client with an Accept-Encoding
header that allows the gzip encoding
will receive the file dir/foo.txt.gz
instead of dir/foo.txt
.
If the precompressed file is not available, or the client doesn’t support it,
the uncompressed version will be served instead.
Both the precompressed version and the uncompressed version are expected
to be present in the directory. Different precompressed variants can be combined.
sourcepub fn precompressed_br(self) -> Self
pub fn precompressed_br(self) -> Self
Informs the service that it should also look for a precompressed brotli version of any file in the directory.
Assuming the dir
directory is being served and dir/foo.txt
is requested,
a client with an Accept-Encoding
header that allows the brotli encoding
will receive the file dir/foo.txt.br
instead of dir/foo.txt
.
If the precompressed file is not available, or the client doesn’t support it,
the uncompressed version will be served instead.
Both the precompressed version and the uncompressed version are expected
to be present in the directory. Different precompressed variants can be combined.
sourcepub fn precompressed_deflate(self) -> Self
pub fn precompressed_deflate(self) -> Self
Informs the service that it should also look for a precompressed deflate version of any file in the directory.
Assuming the dir
directory is being served and dir/foo.txt
is requested,
a client with an Accept-Encoding
header that allows the deflate encoding
will receive the file dir/foo.txt.zz
instead of dir/foo.txt
.
If the precompressed file is not available, or the client doesn’t support it,
the uncompressed version will be served instead.
Both the precompressed version and the uncompressed version are expected
to be present in the directory. Different precompressed variants can be combined.
sourcepub fn precompressed_zstd(self) -> Self
pub fn precompressed_zstd(self) -> Self
Informs the service that it should also look for a precompressed zstd version of any file in the directory.
Assuming the dir
directory is being served and dir/foo.txt
is requested,
a client with an Accept-Encoding
header that allows the zstd encoding
will receive the file dir/foo.txt.zst
instead of dir/foo.txt
.
If the precompressed file is not available, or the client doesn’t support it,
the uncompressed version will be served instead.
Both the precompressed version and the uncompressed version are expected
to be present in the directory. Different precompressed variants can be combined.
sourcepub fn fallback<F2>(self, new_fallback: F2) -> ServeDir<F2>
pub fn fallback<F2>(self, new_fallback: F2) -> ServeDir<F2>
Set the fallback service.
This service will be called if there is no file at the path of the request.
The status code returned by the fallback will not be altered. Use
ServeDir::not_found_service
to set a fallback and always respond with 404 Not Found
.
Example
This can be used to respond with a different file:
use tower_http::services::{ServeDir, ServeFile};
let service = ServeDir::new("assets")
// respond with `not_found.html` for missing files
.fallback(ServeFile::new("assets/not_found.html"));
// Run our service using `hyper`
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
hyper::Server::bind(&addr)
.serve(tower::make::Shared::new(service))
.await
.expect("server error");
sourcepub fn not_found_service<F2>(self, new_fallback: F2) -> ServeDir<SetStatus<F2>>
pub fn not_found_service<F2>(self, new_fallback: F2) -> ServeDir<SetStatus<F2>>
Set the fallback service and override the fallback’s status code to 404 Not Found
.
This service will be called if there is no file at the path of the request.
Example
This can be used to respond with a different file:
use tower_http::services::{ServeDir, ServeFile};
let service = ServeDir::new("assets")
// respond with `404 Not Found` and the contents of `not_found.html` for missing files
.not_found_service(ServeFile::new("assets/not_found.html"));
// Run our service using `hyper`
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
hyper::Server::bind(&addr)
.serve(tower::make::Shared::new(service))
.await
.expect("server error");
Setups like this are often found in single page applications.
sourcepub fn call_fallback_on_method_not_allowed(self, call_fallback: bool) -> Self
pub fn call_fallback_on_method_not_allowed(self, call_fallback: bool) -> Self
Customize whether or not to call the fallback for requests that aren’t GET
or HEAD
.
Defaults to not calling the fallback and instead returning 405 Method Not Allowed
.
sourcepub fn try_call<ReqBody, FResBody>(
&mut self,
req: Request<ReqBody>
) -> ResponseFuture<ReqBody, F> ⓘwhere
F: Service<Request<ReqBody>, Response = Response<FResBody>, Error = Infallible> + Clone,
F::Future: Send + 'static,
FResBody: Body<Data = Bytes> + Send + 'static,
FResBody::Error: Into<Box<dyn Error + Send + Sync>>,
pub fn try_call<ReqBody, FResBody>( &mut self, req: Request<ReqBody> ) -> ResponseFuture<ReqBody, F> ⓘwhere F: Service<Request<ReqBody>, Response = Response<FResBody>, Error = Infallible> + Clone, F::Future: Send + 'static, FResBody: Body<Data = Bytes> + Send + 'static, FResBody::Error: Into<Box<dyn Error + Send + Sync>>,
Call the service and get a future that contains any std::io::Error
that might have
happened.
By default <ServeDir as Service<_>>::call
will handle IO errors and convert them into
responses. It does that by converting std::io::ErrorKind::NotFound
and
std::io::ErrorKind::PermissionDenied
to 404 Not Found
and any other error to 500 Internal Server Error
. The error will also be logged with tracing
.
If you want to manually control how the error response is generated you can make a new
service that wraps a ServeDir
and calls try_call
instead of call
.
Example
use tower_http::services::ServeDir;
use std::{io, convert::Infallible};
use http::{Request, Response, StatusCode};
use http_body::{combinators::UnsyncBoxBody, Body as _};
use hyper::Body;
use bytes::Bytes;
use tower::{service_fn, ServiceExt, BoxError};
async fn serve_dir(
request: Request<Body>
) -> Result<Response<UnsyncBoxBody<Bytes, BoxError>>, Infallible> {
let mut service = ServeDir::new("assets");
// You only need to worry about backpressure, and thus call `ServiceExt::ready`, if
// your adding a fallback to `ServeDir` that cares about backpressure.
//
// Its shown here for demonstration but you can do `service.try_call(request)`
// otherwise
let ready_service = match ServiceExt::<Request<Body>>::ready(&mut service).await {
Ok(ready_service) => ready_service,
Err(infallible) => match infallible {},
};
match ready_service.try_call(request).await {
Ok(response) => {
Ok(response.map(|body| body.map_err(Into::into).boxed_unsync()))
}
Err(err) => {
let body = Body::from("Something went wrong...")
.map_err(Into::into)
.boxed_unsync();
let response = Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(body)
.unwrap();
Ok(response)
}
}
}
// Run our service using `hyper`
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
hyper::Server::bind(&addr)
.serve(tower::make::Shared::new(service_fn(serve_dir)))
.await
.expect("server error");
Trait Implementations§
source§impl<ReqBody, F, FResBody> Service<Request<ReqBody>> for ServeDir<F>where
F: Service<Request<ReqBody>, Response = Response<FResBody>, Error = Infallible> + Clone,
F::Future: Send + 'static,
FResBody: Body<Data = Bytes> + Send + 'static,
FResBody::Error: Into<Box<dyn Error + Send + Sync>>,
impl<ReqBody, F, FResBody> Service<Request<ReqBody>> for ServeDir<F>where F: Service<Request<ReqBody>, Response = Response<FResBody>, Error = Infallible> + Clone, F::Future: Send + 'static, FResBody: Body<Data = Bytes> + Send + 'static, FResBody::Error: Into<Box<dyn Error + Send + Sync>>,
Auto Trait Implementations§
impl<F> RefUnwindSafe for ServeDir<F>where F: RefUnwindSafe,
impl<F> Send for ServeDir<F>where F: Send,
impl<F> Sync for ServeDir<F>where F: Sync,
impl<F> Unpin for ServeDir<F>where F: Unpin,
impl<F> UnwindSafe for ServeDir<F>where F: UnwindSafe,
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere T: ?Sized,
source§impl<T, Request> ServiceExt<Request> for Twhere
T: Service<Request> + ?Sized,
impl<T, Request> ServiceExt<Request> for Twhere T: Service<Request> + ?Sized,
source§fn ready(&mut self) -> Ready<'_, Self, Request>where
Self: Sized,
fn ready(&mut self) -> Ready<'_, Self, Request>where Self: Sized,
source§fn ready_and(&mut self) -> Ready<'_, Self, Request>where
Self: Sized,
fn ready_and(&mut self) -> Ready<'_, Self, Request>where Self: Sized,
ServiceExt::ready
method insteadsource§fn ready_oneshot(self) -> ReadyOneshot<Self, Request>where
Self: Sized,
fn ready_oneshot(self) -> ReadyOneshot<Self, Request>where Self: Sized,
source§fn oneshot(self, req: Request) -> Oneshot<Self, Request>where
Self: Sized,
fn oneshot(self, req: Request) -> Oneshot<Self, Request>where Self: Sized,
Service
, calling with the providing request once it is ready.source§fn call_all<S>(self, reqs: S) -> CallAll<Self, S>where
Self: Sized,
Self::Error: Into<Box<dyn Error + Send + Sync, Global>>,
S: Stream<Item = Request>,
fn call_all<S>(self, reqs: S) -> CallAll<Self, S>where Self: Sized, Self::Error: Into<Box<dyn Error + Send + Sync, Global>>, S: Stream<Item = Request>,
source§fn and_then<F>(self, f: F) -> AndThen<Self, F>where
Self: Sized,
F: Clone,
fn and_then<F>(self, f: F) -> AndThen<Self, F>where Self: Sized, F: Clone,
poll_ready
method. Read moresource§fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>where
Self: Sized,
F: FnOnce(Self::Response) -> Response + Clone,
fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>where Self: Sized, F: FnOnce(Self::Response) -> Response + Clone,
poll_ready
method. Read moresource§fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>where
Self: Sized,
F: FnOnce(Self::Error) -> Error + Clone,
fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>where Self: Sized, F: FnOnce(Self::Error) -> Error + Clone,
poll_ready
method. Read moresource§fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>where
Self: Sized,
Error: From<Self::Error>,
F: FnOnce(Result<Self::Response, Self::Error>) -> Result<Response, Error> + Clone,
fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Result<Response, Error> + Clone,
Result<Self::Response, Self::Error>
)
to a different value, regardless of whether the future succeeds or
fails. Read more