Serving static assets
Serving static assets (such as HTML files, JS files, or CSS files) is a very common task for a web application. We can make Rocket serve files as well. Let's create the first function to serve a favicon. Previously you might have noticed that some web browsers requested a favicon file from our server, even though we did not explicitly mention it on our served HTML page. Let's look at the steps:
- In the application root folder, create a folder named
static
. Inside thestatic
folder, add a file namedfavicon.png
. You can find samplefavicon.png
files on the internet or use the file from the sample source code for this chapter. - In
src/main.rs
, add a new route:routes![ ... routes::favicon, ],
- In
src/routes/mod.rs
, add a new route handling function to servefavicon.png
:use rocket::fs::{relative, NamedFile}; use std::path::Path; ... #[get("/favicon.png")] pub async fn favicon() ->...