pub struct ServeDir<F = DefaultServeDirFallback, B = TokioBackend> { /* 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<B: Backend> ServeDir<DefaultServeDirFallback, B>
impl<B: Backend> ServeDir<DefaultServeDirFallback, B>
Source§impl<F, B: Backend> ServeDir<F, B>
impl<F, B: Backend> ServeDir<F, B>
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 html_as_default_extension(self, append: bool) -> Self
pub fn html_as_default_extension(self, append: bool) -> Self
If the requested path doesn’t specify a file extension, append .html.
Defaults to false.
Sourcepub fn redirect_path_prefix(self, prefix: impl Into<String>) -> Self
pub fn redirect_path_prefix(self, prefix: impl Into<String>) -> Self
Sets a path to be prepended when performing a trailing slash redirect.
This is useful when you want to serve the files at another location than /, for example
when you are using multiple services and want this instance to handle /static/<path>.
In that example, you should pass in /static so that a trailing slash redirect does not
redirect to /<path>/ but instead to /static/<path>/
The default is the empty string.
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, B>
pub fn fallback<F2>(self, new_fallback: F2) -> ServeDir<F2, B>
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>, B>
pub fn not_found_service<F2>( self, new_fallback: F2, ) -> ServeDir<SetStatus<F2>, B>
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 in case the tracing
crate feature is enabled.
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
// you are 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, B> Service<Request<ReqBody>> for ServeDir<F, B>
impl<ReqBody, F, FResBody, B> Service<Request<ReqBody>> for ServeDir<F, B>
Source§type Response = Response<ResponseBody>
type Response = Response<ResponseBody>
Source§type Error = Infallible
type Error = Infallible
Auto Trait Implementations§
impl<F = DefaultServeDirFallback, B = TokioBackend> !Freeze for ServeDir<F, B>
impl<F, B> RefUnwindSafe for ServeDir<F, B>where
B: RefUnwindSafe,
F: RefUnwindSafe,
impl<F, B> Send for ServeDir<F, B>
impl<F, B> Sync for ServeDir<F, B>
impl<F, B> Unpin for ServeDir<F, B>
impl<F, B> UnsafeUnpin for ServeDir<F, B>where
B: UnsafeUnpin,
F: UnsafeUnpin,
impl<F, B> UnwindSafe for ServeDir<F, B>where
B: UnwindSafe,
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> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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> ServiceExt for T
impl<T> ServiceExt for T
Source§fn propagate_header(self, header: HeaderName) -> PropagateHeader<Self>where
Self: Sized,
fn propagate_header(self, header: HeaderName) -> PropagateHeader<Self>where
Self: Sized,
propagate-header and util only.Source§fn add_extension<T>(self, value: T) -> AddExtension<Self, T>where
Self: Sized,
fn add_extension<T>(self, value: T) -> AddExtension<Self, T>where
Self: Sized,
add-extension and util only.Source§fn map_request_body<F>(self, f: F) -> MapRequestBody<Self, F>where
Self: Sized,
fn map_request_body<F>(self, f: F) -> MapRequestBody<Self, F>where
Self: Sized,
map-request-body and util only.Source§fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>where
Self: Sized,
fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>where
Self: Sized,
map-response-body and util only.Source§fn compression(self) -> Compression<Self>where
Self: Sized,
fn compression(self) -> Compression<Self>where
Self: Sized,
util and (crate features compression-br or compression-deflate or compression-gzip or compression-zstd) only.Source§fn decompression(self) -> Decompression<Self>where
Self: Sized,
fn decompression(self) -> Decompression<Self>where
Self: Sized,
util and (crate features decompression-br or decompression-deflate or decompression-gzip or decompression-zstd) only.Source§fn trace_for_http(self) -> Trace<Self, HttpMakeClassifier>where
Self: Sized,
fn trace_for_http(self) -> Trace<Self, HttpMakeClassifier>where
Self: Sized,
trace and util only.Source§fn trace_for_grpc(self) -> Trace<Self, GrpcMakeClassifier>where
Self: Sized,
fn trace_for_grpc(self) -> Trace<Self, GrpcMakeClassifier>where
Self: Sized,
trace and util only.Source§fn follow_redirects(self) -> FollowRedirect<Self, Standard>where
Self: Sized,
fn follow_redirects(self) -> FollowRedirect<Self, Standard>where
Self: Sized,
follow-redirect and util only.Source§fn sensitive_headers(
self,
headers: impl IntoIterator<Item = HeaderName>,
) -> SetSensitiveHeaders<Self>where
Self: Sized,
fn sensitive_headers(
self,
headers: impl IntoIterator<Item = HeaderName>,
) -> SetSensitiveHeaders<Self>where
Self: Sized,
sensitive-headers and util only.Source§fn sensitive_request_headers(
self,
headers: impl IntoIterator<Item = HeaderName>,
) -> SetSensitiveRequestHeaders<Self>where
Self: Sized,
fn sensitive_request_headers(
self,
headers: impl IntoIterator<Item = HeaderName>,
) -> SetSensitiveRequestHeaders<Self>where
Self: Sized,
sensitive-headers and util only.Source§fn sensitive_response_headers(
self,
headers: impl IntoIterator<Item = HeaderName>,
) -> SetSensitiveResponseHeaders<Self>where
Self: Sized,
fn sensitive_response_headers(
self,
headers: impl IntoIterator<Item = HeaderName>,
) -> SetSensitiveResponseHeaders<Self>where
Self: Sized,
sensitive-headers and util only.Source§fn override_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn override_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
set-header and util only.Source§fn append_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn append_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
set-header and util only.Source§fn insert_request_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn insert_request_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
set-header and util only.Source§fn override_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn override_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
set-header and util only.Source§fn append_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn append_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
set-header and util only.Source§fn insert_response_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn insert_response_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
set-header and util only.Source§fn set_request_id<M>(
self,
header_name: HeaderName,
make_request_id: M,
) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
fn set_request_id<M>(
self,
header_name: HeaderName,
make_request_id: M,
) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
request-id and util only.Source§fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
request-id and util only.x-request-id as the header name. Read moreSource§fn propagate_request_id(
self,
header_name: HeaderName,
) -> PropagateRequestId<Self>where
Self: Sized,
fn propagate_request_id(
self,
header_name: HeaderName,
) -> PropagateRequestId<Self>where
Self: Sized,
request-id and util only.Source§fn propagate_x_request_id(self) -> PropagateRequestId<Self>where
Self: Sized,
fn propagate_x_request_id(self) -> PropagateRequestId<Self>where
Self: Sized,
request-id and util only.x-request-id as the header name. Read moreSource§fn catch_panic(self) -> CatchPanic<Self, DefaultResponseForPanic>where
Self: Sized,
fn catch_panic(self) -> CatchPanic<Self, DefaultResponseForPanic>where
Self: Sized,
catch-panic and util only.500 Internal Server responses. Read moreSource§fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>where
Self: Sized,
fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>where
Self: Sized,
limit and util only.413 Payload Too Large responses. Read moreSource§fn trim_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
fn trim_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
normalize-path and util only.Source§fn append_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
fn append_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
normalize-path and util only.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_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 it with the provided 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