Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 or does Rocket?

like image 821
Hendrik Jan Avatar asked Feb 20 '18 22:02

Hendrik Jan


2 Answers

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.

like image 190
Dan Hulme Avatar answered Sep 21 '22 17:09

Dan Hulme


By default, Rocket will respond with text/plain so you have to override it using the content module it provides.

You can use the Html responder as such:

use rocket::response::content;

#[get("/")]
fn page_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>
    "#)
}
like image 40
squiguy Avatar answered Sep 18 '22 17:09

squiguy