Search code examples
htmlrustrust-rocket

How do I return HTML content with Rocket 0.5?


I am trying to build a simple webserver with HTML. This is my code:

use rocket::*;
use rocket::response::content::Html;

#[get("/")]
fn index() -> content::Html<&'static str> {
    content::Html(r#"
        <title>GCD Calculator</title>
        <form action="/gcd" method="post">
            <input type="text" name="n" />
            <input type="text" name="n" />
            <button type="submit">Compute GCD</button>
        </form>
    "#)
}

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

But it returns the error:

   Compiling hello-rocket v0.1.0 (/home/garuda/dev/Rust/Rocket/hello-rocket)
error[E0432]: unresolved import `rocket::response::content::Html`
 --> src/main.rs:2:5
  |
2 | use rocket::response::content::Html;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `Html` in `response::content`

error[E0433]: failed to resolve: use of undeclared crate or module `content`
 --> src/main.rs:5:15
  |
5 | fn index() -> content::Html<&'static str> {
  |               ^^^^^^^ use of undeclared crate or module `content`

error[E0433]: failed to resolve: use of undeclared crate or module `content`
 --> src/main.rs:6:5
  |
6 |     content::Html(r#"
  |     ^^^^^^^ use of undeclared crate or module `content`

Some errors have detailed explanations: E0432, E0433.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `hello-rocket` due to 3 previous errors

I know for sure that this module exists because here it is in the docs.


Solution

  • In the (preview) Rocket 0.5.0-rc.2, the struct Html was renamed to RawHtml. Replace Html with RawHtml and it'll work.

    See also the changelog:

    • Content-Type content responder type names are now prefixed with Raw.