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?
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.
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>
"#)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With