ServeDir

Struct ServeDir 

Source
pub struct ServeDir<FS, F = DefaultServeDirFallback> { /* private fields */ }
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
  • We don’t have necessary permissions to read the file

§Example

use http_dir::ServeDir;
use http_dir::fs::disk::DiskFilesystem;

// This will serve files in the "assets" directory and
// its subdirectories
let service = ServeDir::new(DiskFilesystem::from("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<FS> ServeDir<FS, DefaultServeDirFallback>

Source

pub fn new(filesystem: FS) -> Self

Create a new ServeDir.

Source§

impl<FS, F> ServeDir<FS, F>

Source

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.

Source

pub fn with_buf_chunk_size(self, chunk_size: usize) -> Self

Set a specific read buffer chunk size.

The default capacity is 64kb.

Source

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.

Source

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.

Source

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.

Source

pub fn fallback<F2>(self, new_fallback: F2) -> ServeDir<FS, 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 http_dir::{ServeDir, ServeFile};
use http_dir::fs::disk::DiskFilesystem;

let filesystem = DiskFilesystem::from("assets");

let service = ServeDir::new(filesystem.clone())
    // respond with `not_found.html` for missing files
    .fallback(ServeFile::new("not_found.html", filesystem));

// 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");
Source

pub fn not_found_service<F2>( self, new_fallback: F2, ) -> ServeDir<FS, 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 http_dir::{ServeDir, ServeFile};
use http_dir::fs::disk::DiskFilesystem;

let filesystem = DiskFilesystem::from("assets");

let service = ServeDir::new(filesystem.clone())
    // respond with `404 Not Found` and the contents of `not_found.html` for missing files
    .not_found_service(ServeFile::new("/not_found.html", filesystem));

// 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.

Source

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.

Trait Implementations§

Source§

impl<FS: Clone, F: Clone> Clone for ServeDir<FS, F>

Source§

fn clone(&self) -> ServeDir<FS, F>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<FS: Debug, F: Debug> Debug for ServeDir<FS, F>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<ReqBody, F, FResBody, FS> Service<Request<ReqBody>> for ServeDir<FS, F>
where F: Service<Request<ReqBody>, Response = Response<FResBody>> + Clone, F::Error: Into<Error>, F::Future: Send, FResBody: Body<Data = Bytes> + Send + 'static, FResBody::Error: Into<Box<dyn Error + Send + Sync>>, FS: Filesystem + Clone + Send + Sync, FS::File: 'static,

Source§

type Response = Response<UnsyncBoxBody<Bytes, Error>>

Responses given by the service.
Source§

type Error = Error

Errors produced by the service.
Source§

type Future = impl Future<Output = Result<<ServeDir<FS, F> as Service<Request<ReqBody>>>::Response, <ServeDir<FS, F> as Service<Request<ReqBody>>>::Error>>

The future response value.
Source§

fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Poll::Ready(Ok(())) when the service is able to process requests. Read more
Source§

fn call(&mut self, req: Request<ReqBody>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementations§

§

impl<FS, F = DefaultServeDirFallback> !Freeze for ServeDir<FS, F>

§

impl<FS, F> RefUnwindSafe for ServeDir<FS, F>

§

impl<FS, F> Send for ServeDir<FS, F>
where FS: Send, F: Send,

§

impl<FS, F> Sync for ServeDir<FS, F>
where FS: Sync, F: Sync,

§

impl<FS, F> Unpin for ServeDir<FS, F>
where FS: Unpin, F: Unpin,

§

impl<FS, F> UnwindSafe for ServeDir<FS, F>
where FS: UnwindSafe, F: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.