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

View File

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

View File

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

View File

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

View File

@ -43,7 +43,7 @@ use response::{Response, Stream};
/// ///
/// * **String** /// * **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 /// of the response, which is fixed size and not streamed. To stream a
/// string, use `Stream::from(Cursor::new(string))`. /// 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`. /// containing the string `self`. Always returns `Ok`.
impl Responder<'static> for String { impl Responder<'static> for String {
fn respond(self) -> Result<Response<'static>, Status> { fn respond(self) -> Result<Response<'static>, Status> {
Response::build() Response::build()
.header(ContentType::HTML) .header(ContentType::Plain)
.sized_body(Cursor::new(self)) .sized_body(Cursor::new(self))
.ok() .ok()
} }

View File

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