rusthttp-headerscontent-typerust-rocket

Why is Rocket not setting content-type text/html?


I am using the Rust Rocket framework for generating a simple webpage.

When go the the index page /:

#[get("/")]
fn page_index() -> &'static str {
    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>
    "#
}

The server console tells me

GET / text/html:
=> Matched: GET /
=> Outcome: Success
=> Response succeeded.

But my browser tells me the Content-Type is text/plain. How do I get Rocket to correctly respond with text/html. Am I doing anything wrong?


Solution

  • The guide about responders explains how to set the Content-Type of your response. In particular, you need rocket::response::content::Html:

    use rocket::response::content::Html;
    #[get("/")]
    fn page_index() -> Html<&'static str> {
        Html(r"<html>...</html>")
    }
    

    Note that you actually have to return an HTML document if you're going to set the Content-Type to "text/html". What you've posted in your example code is just a fragment of HTML. In practice, it's much easier to either put your HTML into a static foo.html file and use NamedFile to serve it directly (which automatically sets the Content-Type), or use templates.