Use 'ContentType::Plain' for 'String' responses.

Resolves #49.
This commit is contained in:
Sergio Benitez 2017-01-31 02:43:19 -08:00
parent 724446cda4
commit 374593c2f0
6 changed files with 23 additions and 26 deletions

View File

@ -11,7 +11,7 @@ mod tests;
use rocket::{Request, Error};
use rocket::http::ContentType;
use rocket::response::content::JSON;
use rocket::response::content;
#[derive(Debug, Serialize, Deserialize)]
struct Person {
@ -22,26 +22,28 @@ struct Person {
// This shows how to manually serialize some JSON, but in a real application,
// we'd use the JSON contrib type.
#[get("/<name>/<age>", format = "application/json")]
fn hello(content_type: ContentType, name: String, age: i8) -> JSON<String> {
fn hello(content_type: ContentType, name: String, age: i8) -> content::JSON<String> {
let person = Person {
name: name,
age: age,
};
println!("ContentType: {}", content_type);
JSON(serde_json::to_string(&person).unwrap())
content::JSON(serde_json::to_string(&person).unwrap())
}
#[error(404)]
fn not_found(_: Error, request: &Request) -> String {
if !request.content_type().is_json() {
fn not_found(_: Error, request: &Request) -> content::HTML<String> {
let html = if !request.content_type().is_json() {
format!("<p>This server only supports JSON requests, not '{}'.</p>",
request.content_type())
} else {
format!("<p>Sorry, '{}' is an invalid path! Try \
/hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
request.uri())
}
};
content::HTML(html)
}
fn main() {

View File

@ -3,8 +3,9 @@
extern crate rocket;
#[cfg(test)]
mod tests;
#[cfg(test)] mod tests;
use rocket::response::content;
#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: i8) -> String {
@ -12,10 +13,10 @@ fn hello(name: &str, age: i8) -> String {
}
#[error(404)]
fn not_found(req: &rocket::Request) -> String {
format!("<p>Sorry, but '{}' is not a valid path!</p>
fn not_found(req: &rocket::Request) -> content::HTML<String> {
content::HTML(format!("<p>Sorry, but '{}' is not a valid path!</p>
<p>Try visiting /hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
req.uri())
req.uri()))
}
fn main() {

View File

@ -43,26 +43,21 @@ mod test {
let rocket = rocket::ignite()
.mount("/", routes![super::header_count]);
let num_headers = headers.len();
let mut req = MockRequest::new(Get, "/");
for header in headers {
for header in headers.iter().cloned() {
req = req.header(header);
}
let mut response = req.dispatch_with(&rocket);
let expect = format!("Your request contained {} headers!", num_headers);
let expect = format!("Your request contained {} headers!", headers.len());
assert_eq!(response.body().and_then(|b| b.into_string()), Some(expect));
}
#[test]
fn test_n_headers() {
for i in 0..50 {
let mut headers = vec![];
for j in 0..i {
let string = format!("{}", j);
headers.push(Header::new(string.clone(), string));
}
let headers = (0..i).map(|n| Header::new(n.to_string(), n.to_string()))
.collect();
test_header_count(headers);
}

View File

@ -19,13 +19,13 @@ const HOST: &'static str = "http://localhost:8000";
const ID_LENGTH: usize = 3;
#[post("/", data = "<paste>")]
fn upload(paste: Data) -> io::Result<content::Plain<String>> {
fn upload(paste: Data) -> io::Result<String> {
let id = PasteID::new(ID_LENGTH);
let filename = format!("upload/{id}", id = id);
let url = format!("{host}/{id}\n", host = HOST, id = id);
paste.stream_to_file(Path::new(&filename))?;
Ok(content::Plain(url))
Ok(url)
}
#[get("/<id>")]

View File

@ -43,7 +43,7 @@ use response::{Response, Stream};
///
/// * **String**
///
/// Sets the `Content-Type`t to `text/html`. The string is used as the body
/// Sets the `Content-Type`t to `text/plain`. The string is used as the body
/// of the response, which is fixed size and not streamed. To stream a
/// string, use `Stream::from(Cursor::new(string))`.
///
@ -188,12 +188,12 @@ impl<'r> Responder<'r> for &'r str {
}
}
/// Returns a response with Content-Type `text/html` and a fized-size body
/// Returns a response with Content-Type `text/html` and a fixed-size body
/// containing the string `self`. Always returns `Ok`.
impl Responder<'static> for String {
fn respond(self) -> Result<Response<'static>, Status> {
Response::build()
.header(ContentType::HTML)
.header(ContentType::Plain)
.sized_body(Cursor::new(self))
.ok()
}

View File

@ -25,7 +25,6 @@ mod tests {
fn check_decoding(raw: &str, decoded: &str) {
let rocket = rocket::ignite().mount("/", routes![bug]);
let mut req = MockRequest::new(Post, "/")
.header(ContentType::Form)
.body(format!("form_data={}", raw));