I'm trying to use the Rust Rocket framework as a backend for hosting my website, but I'm struggling with serving basic HTML files and their associated files.
As far as things go, this is the code for my "website". I'm really not sure how to do this, being new to backend development I thought I'd see if there's an answer here.
#[macro_use] extern crate rocket; use std::fs::File; use rocket::{response::{Redirect}, fs::FileServer}; #[get("/")] fn index() -> Redirect { let redirect = Redirect::to(uri!("/home")); redirect } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![index]) }
I'm not sure what the best way to build the frontend files is. Any advice/help is appreciated. Please go easy on me as I have little experience in backend development.
I've tried the static examples listed on GitHub, however, I think I've run into a problem: I can view the HTML page, but the images, CSS, and JavaScript files are not served correctly.
I came up with a simpler solution. You can simply use
FileServer
to host your static files like this:So whenever my HTML template tries to call a CSS file, Rocket serves the CSS file from the
/templates/css
directory.This is the code that works best for me. I want to explain this for those of you who might be trying to get into backend web development (especially Rust).
I'll start with the first part.
^ This is just our declaration of what I need to use.
^ This section is used to redirect blank index URLs to not give a 404 and go to URLs with "/home" at the end. This is just my personal preference, but now you know how to do it too!
Finally, I determined how to specifically open different files by looking at the Rust parser example for NamedFile.
^ This section is used to handle other files such as CSS and JavaScript linked in the HTML document. I guess this is not a very secure approach, but for a portfolio site I don't need very strong security.
^ Finally, you just install the route. Doing this seems to work for me. I'm sure smarter, more experienced people can explain it in a more elegant way than I can, but if you're in a pinch like I was and you're at your wits' end, hopefully this is a much-needed life preserver when you're drowning.