Search code examples
rustrust-rocket

How do I display a HTML webpage by file name in Rocket?


I am able to make a HTML webpage but only with the content directly in my .rs file.

use rocket::*;
use rocket::response::content::RawHtml;

#[get("/")]
fn index() -> RawHtml<&'static str> {
    RawHtml(r#"<h1>Hello world</h1>"#)
}

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

How do I separate it giving a link to the file to be displayed to Rocket?


Solution

  • If you want the HTML document compiled in to your program so that it has no dependencies on external files, you can use the standard include_str! macro:

    RawHtml(include_str!("index.html"))
    

    This will look for index.html in the same directory as the .rs file the macro appears in during compilation, and insert the contents as a static string literal.

    Alternatively, if you want the program to look for a file on disk at runtime, you can use Rocket's NamedFile responder.