Using Rocket, I am getting an error loading a CSS file. How do I properly do it?

40 Views Asked by At

so I'm currently learning Rust and Rocket for web development, however, I am getting an error while loading a css file to my submit.html file.

My directory layout is as follows:

project_root/
|-- src/
|   |-- main.rs
|-- static/
|   |-- css/
|   |   |-- submit.css
|   |   |-- index.css
|   |-- index.html
|-- templates/
|   |-- submit.html

Next, my Rust code in the main.rs file looks like this:

use rocket::http::Status;
use rocket::response::content::RawHtml;
use tera::Context;
use tera::Tera;
use rand::Rng;
use rocket::fs::FileServer;

#[macro_use]
extern crate rocket;

const CHARACTERS: &str = "abcdefghijklmnopqrstuvwxyz1234567890";

#[get("/submit?<url>")]
fn submit(url: String) -> RawHtml<String> {
    let mut length = 0;
    let mut shortened_url = String::new();

    loop {
        length += 1;

        shortened_url.push(get_random_char());
        if length == 6 {
            break;
        }
    }

    let tera = Tera::new("templates/**/*").expect("Failed to create Tera instance");

    let mut context = Context::new();
    context.insert("url", &shortened_url);

    let rendered_template = tera.render("submit.html", &context).expect("Failed to render template");
    RawHtml(rendered_template)
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![submit])
        .mount("/", FileServer::from("static"))
}

// Functions not related to rocket:
fn get_random_char() -> char {
    let mut rng = rand::thread_rng();
    let index = rng.gen_range(0..CHARACTERS.len());

    CHARACTERS.chars().nth(index).expect("Failed to get random character")
}

So, what happens here is when they visit the root, https://localhost:8000/ the CSS file for index.css loads perfectly fine and the css is actually working. However, when they visit localhost:8000/submit?url=https://example.com, i get:

No matching routes for GET /static/css/submit.css text/css.

Although I am linking everything in my submit.html file perfectly fine to the submit.css stylesheet.

Anyone know why this is happening?

What I tried doing what simply just doing what I did with the index.css and index.html file because it worked with just loading with FileServer::from("static"), but clearly that isn't working. Anyone know why? Thanks a lot!

0

There are 0 best solutions below