We'll want to add assets to our project such as images, css and perhaps javascript (but hopefully not javascript).
Cache busting is where we invalidate a cached file and force the browser to retrieve the file from the server. We can instruct the browser to bypass the cache by simply changing the filename. To the browser, this is a completely new resource so it will fetch the resource from the server. The most common way to do this is to add the hash of the file to the URL.
We can also generate some code so the assets are available in our Rust pages and then we get the added benefit that if the files are deleted or names are changed we get compiler errors.
Add the following to crates/web-assets/images/favicon.svg
We'll use Cache Busters to generate code that allows to access assets in a typesafe way. Cache busters also handles hashing so that we never have to worry about the browser deploying the wrong CSS or Images.
Create a crates/web-assets/build.rs
so that the main
method looks like the following.
use generate_static_files_code;
use env;
use PathBuf;
Setup our dependencies
build.rs
will now take our assets and turn them into rust functions. It handles creating a hash for the assets so we get good browser cache busting.
We needs to export our assets from our crate overwrite the crates/web-assets/src/lib.rs
include!;
pub use statics as files;
Back to our web-server
crate.
create a new file crates/web-server/src/static_files.rs
and add the following function.
use Body;
use ;
use IntoResponse;
use TypedPath;
use Deserialize;
use ReaderStream;
use StaticFile;
pub async
And add the following route in crates/web-server/src/main.rs
in the section where we defined our routes.
.route
And change the mod
section so it includes the following.
Let's add the image to the page.
In our crates/web-pages
directory run...
And update the crates/web-pages/src/root.rs
so it includes our image.
use crate::;
use User;
use *;
use favicon_svg;
Update your just file so any changes to the web-pages
crate are reflected in the browser.
Add this -w crates/web-pages
.
That was a lot of work to put images on the screen but don't forget we now have a typesafe way to access images.