pub struct FileServer { /* private fields */ }
Expand description
Custom handler for serving static files.
This handler makes is simple to serve static files from a directory on the
local file system. To use it, construct a FileServer
using
FileServer::new()
, then mount
the handler.
use rocket::fs::FileServer;
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", FileServer::new("/www/static"))
}
When mounted, the handler serves files from the specified path. If a
requested file does not exist, the handler forwards the request with a
404
status.
By default, the route has a rank of 10
which can be changed with
FileServer::rank()
.
§Customization
FileServer
works through a pipeline of rewrites in which a requested
path is transformed into a PathBuf
via Segments::to_path_buf()
and
piped through a series of Rewriter
s to obtain a final Rewrite
which
is then used to generate a final response. See Rewriter
for complete
details on implementing your own Rewriter
s.
§Example
Serve files from the /static
directory on the local file system at the
/public
path:
use rocket::fs::FileServer;
#[launch]
fn rocket() -> _ {
rocket::build().mount("/public", FileServer::new("/static"))
}
Requests for files at /public/<path..>
will be handled by returning the
contents of /static/<path..>
. Requests for directories will return the
contents of index.html
.
§Relative Paths
In the example above, /static
is an absolute path. If your static files
are stored relative to your crate and your project is managed by Cargo, use
the relative!
macro to obtain a path that is relative to your crate’s
root. For example, to serve files in the static
subdirectory of your crate
at /
, you might write:
use rocket::fs::{FileServer, relative};
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", FileServer::new(relative!("static")))
}
Implementations§
Source§impl FileServer
impl FileServer
Sourcepub fn new<P: AsRef<Path>>(path: P) -> Self
pub fn new<P: AsRef<Path>>(path: P) -> Self
Constructs a new FileServer
that serves files from the file system
path
with the following rewrites:
|f, _| f.is_visible()
: Serve only visible files (hide dotfiles).Prefix::checked(path)
: Prefix requests withpath
.TrailingDirs
: Ensure directory have a trailing slash.DirIndex::unconditional("index.html")
: Serve$dir/index.html
for requests to directory$dir
.
If you don’t want to serve index files or want a different index file,
use Self::without_index
. To customize the entire request to file
path rewrite pipeline, use Self::identity
.
§Example
use rocket::fs::FileServer;
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", FileServer::new("/www/static"))
}
Sourcepub fn without_index<P: AsRef<Path>>(path: P) -> Self
pub fn without_index<P: AsRef<Path>>(path: P) -> Self
Exactly like FileServer::new()
except it does not serve directory
index files via DirIndex
. It rewrites with the following:
|f, _| f.is_visible()
: Serve only visible files (hide dotfiles).Prefix::checked(path)
: Prefix requests withpath
.TrailingDirs
: Ensure directory have a trailing slash.
§Example
Constructs a default file server to serve files from ./static
using
index.txt
as the index file if index.html
doesn’t exist.
use rocket::fs::{FileServer, rewrite::DirIndex};
#[launch]
fn rocket() -> _ {
let server = FileServer::new("static")
.rewrite(DirIndex::if_exists("index.html"))
.rewrite(DirIndex::unconditional("index.txt"));
rocket::build()
.mount("/", server)
}
Sourcepub fn identity() -> Self
pub fn identity() -> Self
Constructs a new FileServer
with no rewrites.
Without any rewrites, a FileServer
will try to serve the requested
file from the current working directory. In other words, it represents
the identity rewrite. For example, a request GET /foo/bar
will be
passed through unmodified and thus ./foo/bar
will be served. This is
very unlikely to be what you want.
Prefer to use FileServer::new()
or FileServer::without_index()
whenever possible and otherwise use one or more of the rewrites in
rocket::fs::rewrite
or your own custom rewrites.
§Example
use rocket::fs::{FileServer, rewrite};
#[launch]
fn rocket() -> _ {
// A file server that serves exactly one file: /www/foo.html. The
// file is served irrespective of what's requested.
let server = FileServer::identity()
.rewrite(rewrite::File::checked("/www/foo.html"));
rocket::build()
.mount("/", server)
}
Sourcepub fn rank(self, rank: isize) -> Self
pub fn rank(self, rank: isize) -> Self
Sets the rank of the route emitted by the FileServer
to rank
.
§Example
FileServer::identity()
.rank(5)
Sourcepub fn rewrite<R: Rewriter>(self, rewriter: R) -> Self
pub fn rewrite<R: Rewriter>(self, rewriter: R) -> Self
Add rewriter
to the rewrite pipeline.
§Example
Redirect filtered requests (None
) to /
.
use rocket::fs::{FileServer, rewrite::Rewrite};
use rocket::{request::Request, response::Redirect};
fn redir_missing<'r>(p: Option<Rewrite<'r>>, _req: &Request<'_>) -> Option<Rewrite<'r>> {
Some(p.unwrap_or_else(|| Redirect::temporary(uri!("/")).into()))
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", FileServer::new("static").rewrite(redir_missing))
}
Note that redir_missing
is not a closure in this example. Making it a closure
causes compilation to fail with a lifetime error. It really shouldn’t but it does.
Sourcepub fn filter<F>(self, f: F) -> Self
pub fn filter<F>(self, f: F) -> Self
Adds a rewriter to the pipeline that returns Some
only when the
function f
returns true
, filtering out all other files.
§Example
Allow all files that don’t have a file name or have a file name other than “hidden”.
use rocket::fs::FileServer;
#[launch]
fn rocket() -> _ {
let server = FileServer::new("static")
.filter(|f, _| f.path.file_name() != Some("hidden".as_ref()));
rocket::build()
.mount("/", server)
}
Sourcepub fn map<F>(self, f: F) -> Self
pub fn map<F>(self, f: F) -> Self
Adds a rewriter to the pipeline that maps the current File
to another
Rewrite
using f
. If the current Rewrite
is a Redirect
, it is
passed through without calling f
.
§Example
Append index.txt
to every path.
use rocket::fs::FileServer;
#[launch]
fn rocket() -> _ {
let server = FileServer::new("static")
.map(|f, _| f.map_path(|p| p.join("index.txt")).into());
rocket::build()
.mount("/", server)
}
Trait Implementations§
Source§impl Clone for FileServer
impl Clone for FileServer
Source§fn clone(&self) -> FileServer
fn clone(&self) -> FileServer
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl Debug for FileServer
impl Debug for FileServer
Source§impl From<FileServer> for Vec<Route>
impl From<FileServer> for Vec<Route>
Source§fn from(server: FileServer) -> Self
fn from(server: FileServer) -> Self
Source§impl Handler for FileServer
impl Handler for FileServer
Source§fn handle<'r, 'life0, 'life1, 'async_trait>(
&'life0 self,
req: &'r Request<'life1>,
data: Data<'r>,
) -> Pin<Box<dyn Future<Output = Outcome<'r>> + Send + 'async_trait>>where
Self: 'async_trait,
'r: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
fn handle<'r, 'life0, 'life1, 'async_trait>(
&'life0 self,
req: &'r Request<'life1>,
data: Data<'r>,
) -> Pin<Box<dyn Future<Output = Outcome<'r>> + Send + 'async_trait>>where
Self: 'async_trait,
'r: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
Request
with its associated Data
should be
handled by this handler. Read moreAuto Trait Implementations§
impl Freeze for FileServer
impl !RefUnwindSafe for FileServer
impl Send for FileServer
impl Sync for FileServer
impl Unpin for FileServer
impl !UnwindSafe for FileServer
Blanket Implementations§
Source§impl<T> AsAny for Twhere
T: Any,
impl<T> AsAny for Twhere
T: Any,
fn as_any_ref(&self) -> &(dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
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> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the foreground set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red()
and
green()
, which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg()
:
use yansi::{Paint, Color};
painted.fg(Color::White);
Set foreground color to white using white()
.
use yansi::Paint;
painted.white();
Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.bright_black());
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.bright_green());
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.bright_yellow());
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.bright_magenta());
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.bright_white());
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the background set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red()
and
on_green()
, which have the same functionality but
are pithier.
§Example
Set background color to red using fg()
:
use yansi::{Paint, Color};
painted.bg(Color::Red);
Set background color to red using on_red()
.
use yansi::Paint;
painted.on_red();
Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.on_bright_black());
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.on_bright_green());
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.on_bright_yellow());
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlue
.
§Example
println!("{}", value.on_bright_blue());
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.on_bright_magenta());
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightCyan
.
§Example
println!("{}", value.on_bright_cyan());
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.on_bright_white());
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute
value
.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold()
and
underline()
, which have the same functionality
but are pithier.
§Example
Make text bold using attr()
:
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);
Make text bold using using bold()
.
use yansi::Paint;
painted.bold();
Source§fn underline(&self) -> Painted<&T>
fn underline(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::Underline
.
§Example
println!("{}", value.underline());
Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::RapidBlink
.
§Example
println!("{}", value.rapid_blink());
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi
Quirk
value
.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask()
and
wrap()
, which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk()
:
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);
Enable wrapping using wrap()
.
use yansi::Paint;
painted.wrap();
Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition
value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted
only when both stdout
and stderr
are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);