Struct tower_http::services::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");
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"));
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"));
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> ⓘ
pub fn try_call<ReqBody, FResBody>( &mut self, req: Request<ReqBody> ) -> ResponseFuture<ReqBody, F> ⓘ
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::Body as _;
use http_body_util::{Full, BodyExt, combinators::UnsyncBoxBody};
use bytes::Bytes;
use tower::{service_fn, ServiceExt, BoxError};
async fn serve_dir(
request: Request<Full<Bytes>>
) -> 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<Full<Bytes>>>::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 = Full::from("Something went wrong...")
.map_err(Into::into)
.boxed_unsync();
let response = Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(body)
.unwrap();
Ok(response)
}
}
}
Trait Implementations§
source§impl<ReqBody, F, FResBody> Service<Request<ReqBody>> for ServeDir<F>
impl<ReqBody, F, FResBody> Service<Request<ReqBody>> for ServeDir<F>
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 T
impl<T, Request> ServiceExt<Request> for T
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 and_then<F>(self, f: F) -> AndThen<Self, F>
fn and_then<F>(self, f: F) -> AndThen<Self, F>
poll_ready
method. Read moresource§fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
poll_ready
method. Read moresource§fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
poll_ready
method. Read moresource§fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
Result<Self::Response, Self::Error>
)
to a different value, regardless of whether the future succeeds or
fails. Read more