Skip to content

Commit 4276d67

Browse files
authored
Merge pull request #562 from http-rs/normalize-response
Bring response in line with http-types
2 parents c7a9d50 + 5073c51 commit 4276d67

16 files changed

+124
-186
lines changed

examples/chunked.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
use async_std::fs;
2-
use async_std::io::BufReader;
31
use async_std::task;
4-
use tide::{Response, StatusCode};
2+
use tide::{Body, Response, StatusCode};
53

64
fn main() -> Result<(), std::io::Error> {
75
task::block_on(async {
86
let mut app = tide::new();
97
app.at("/").get(|_| async move {
10-
let file = fs::File::open(file!()).await.unwrap();
11-
let res = Response::new(StatusCode::Ok).body(BufReader::new(file));
8+
let mut res = Response::new(StatusCode::Ok);
9+
res.set_body(Body::from_file(file!()).await.unwrap());
1210
Ok(res)
1311
});
1412
app.listen("127.0.0.1:8080").await?;

examples/cookies.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ async fn retrieve_cookie(cx: Request<()>) -> tide::Result<String> {
88
Ok(format!("hello cookies: {:?}", cx.cookie("hello").unwrap()))
99
}
1010

11-
async fn set_cookie(_req: Request<()>) -> tide::Result {
11+
async fn insert_cookie(_req: Request<()>) -> tide::Result {
1212
let mut res = tide::Response::new(StatusCode::Ok);
13-
res.set_cookie(Cookie::new("hello", "world"));
13+
res.insert_cookie(Cookie::new("hello", "world"));
1414
Ok(res)
1515
}
1616

@@ -25,7 +25,7 @@ fn main() -> Result<(), std::io::Error> {
2525
let mut app = tide::new();
2626

2727
app.at("/").get(retrieve_cookie);
28-
app.at("/set").get(set_cookie);
28+
app.at("/set").get(insert_cookie);
2929
app.at("/remove").get(remove_cookie);
3030
app.listen("127.0.0.1:8080").await?;
3131

examples/graphql.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use async_std::task;
22
use juniper::RootNode;
33
use std::sync::RwLock;
4-
use tide::{Redirect, Request, Response, Server, StatusCode};
4+
use tide::{Body, Redirect, Request, Response, Server, StatusCode};
55

66
#[derive(Clone)]
77
struct User {
@@ -86,16 +86,15 @@ async fn handle_graphql(mut cx: Request<State>) -> tide::Result {
8686
StatusCode::BadRequest
8787
};
8888

89-
let res = Response::new(status)
90-
.body_json(&response)
91-
.expect("be able to serialize the graphql response");
89+
let mut res = Response::new(status);
90+
res.set_body(Body::from_json(&response)?);
9291
Ok(res)
9392
}
9493

9594
async fn handle_graphiql(_: Request<State>) -> tide::Result {
96-
let res = Response::new(StatusCode::Ok)
97-
.body_string(juniper::http::graphiql::graphiql_source("/graphql"))
98-
.set_content_type(tide::http::mime::HTML);
95+
let mut res = Response::new(StatusCode::Ok);
96+
res.set_body(juniper::http::graphiql::graphiql_source("/graphql"));
97+
res.set_content_type(tide::http::mime::HTML);
9998
Ok(res)
10099
}
101100

examples/json.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use async_std::task;
22
use serde::{Deserialize, Serialize};
33
use tide::prelude::*;
4-
use tide::{Request, Response, StatusCode};
4+
use tide::{Body, Request, Response};
55

66
#[derive(Deserialize, Serialize)]
77
struct Cat {
@@ -20,7 +20,9 @@ fn main() -> tide::Result<()> {
2020
name: "chashu".into(),
2121
};
2222

23-
Ok(Response::new(StatusCode::Ok).body_json(&cat)?)
23+
let mut res = Response::new(200);
24+
res.set_body(Body::from_json(&cat)?);
25+
Ok(res)
2426
});
2527

2628
app.at("/animals").get(|_| async {

examples/middleware.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::future::Future;
22
use std::pin::Pin;
33
use std::sync::atomic::{AtomicUsize, Ordering};
44
use std::sync::Arc;
5+
use tide::http::mime;
56
use tide::{After, Before, Middleware, Next, Request, Response, Result, StatusCode};
67

78
#[derive(Debug)]
@@ -70,10 +71,10 @@ impl<State: Send + Sync + 'static> Middleware<State> for RequestCounterMiddlewar
7071
tide::log::trace!("request counter", { count: count });
7172
req.set_ext(RequestCount(count));
7273

73-
let mut response = next.run(req).await?;
74+
let mut res = next.run(req).await?;
7475

75-
response = response.set_header("request-number", count.to_string());
76-
Ok(response)
76+
res.insert_header("request-number", count.to_string());
77+
Ok(res)
7778
})
7879
}
7980
}
@@ -101,14 +102,18 @@ async fn main() -> Result<()> {
101102
app.middleware(After(|result: Result| async move {
102103
let response = result.unwrap_or_else(|e| Response::new(e.status()));
103104
match response.status() {
104-
StatusCode::NotFound => Ok(response
105-
.set_content_type(tide::http::mime::HTML)
106-
.body_string(NOT_FOUND_HTML_PAGE.into())),
107-
108-
StatusCode::InternalServerError => Ok(response
109-
.set_content_type(tide::http::mime::HTML)
110-
.body_string(INTERNAL_SERVER_ERROR_HTML_PAGE.into())),
111-
105+
StatusCode::NotFound => {
106+
let mut res = Response::new(404);
107+
res.set_content_type(mime::HTML);
108+
res.set_body(NOT_FOUND_HTML_PAGE);
109+
Ok(res)
110+
}
111+
StatusCode::InternalServerError => {
112+
let mut res = Response::new(500);
113+
res.set_content_type(mime::HTML);
114+
res.set_body(INTERNAL_SERVER_ERROR_HTML_PAGE);
115+
Ok(res)
116+
}
112117
_ => Ok(response),
113118
}
114119
}));

src/cookies/middleware.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use std::sync::{Arc, RwLock};
1818
/// app.at("/get").get(|cx: Request<()>| async move { Ok(cx.cookie("testCookie").unwrap().value().to_string()) });
1919
/// app.at("/set").get(|_| async {
2020
/// let mut res = Response::new(StatusCode::Ok);
21-
/// res.set_cookie(Cookie::new("testCookie", "NewCookieValue"));
21+
/// res.insert_cookie(Cookie::new("testCookie", "NewCookieValue"));
2222
/// Ok(res)
2323
/// });
2424
/// ```
@@ -69,7 +69,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
6969
// iterate over added and removed cookies
7070
for cookie in jar.delta() {
7171
let encoded_cookie = cookie.encoded().to_string();
72-
res = res.append_header(headers::SET_COOKIE, encoded_cookie);
72+
res.append_header(headers::SET_COOKIE, encoded_cookie);
7373
}
7474
Ok(res)
7575
})

src/lib.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
//! ```no_run
5252
//! # use async_std::task::block_on;
5353
//! # fn main() -> Result<(), std::io::Error> { block_on(async {
54-
//! # use tide::{Request, Response};
54+
//! # use tide::{Body, Request, Response};
5555
//! #
5656
//! #[derive(Debug, serde::Deserialize, serde::Serialize)]
5757
//! struct Counter { count: usize }
@@ -61,7 +61,9 @@
6161
//! let mut counter: Counter = req.body_json().await?;
6262
//! println!("count is {}", counter.count);
6363
//! counter.count += 1;
64-
//! Ok(Response::new(tide::http::StatusCode::Ok).body_json(&counter)?)
64+
//! let mut res = Response::new(200);
65+
//! res.set_body(Body::from_json(&counter)?);
66+
//! Ok(res)
6567
//! });
6668
//! app.listen("127.0.0.1:8080").await?;
6769
//! #

src/redirect.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ impl<T: AsRef<str>> Into<Response> for Redirect<T> {
104104

105105
impl<T: AsRef<str>> Into<Response> for &Redirect<T> {
106106
fn into(self) -> Response {
107-
Response::new(self.status).set_header(LOCATION, self.location.as_ref())
107+
let mut res = Response::new(self.status);
108+
res.insert_header(LOCATION, self.location.as_ref());
109+
res
108110
}
109111
}

src/request.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use async_std::io::{self, prelude::*, BufReader};
1+
use async_std::io::{self, prelude::*};
22
use async_std::task::{Context, Poll};
33
use route_recognizer::Params;
44

@@ -448,8 +448,10 @@ impl<State> Into<http::Request> for Request<State> {
448448
// NOTE: From cannot be implemented for this conversion because `State` needs to
449449
// be constrained by a type.
450450
impl<State: Send + Sync + 'static> Into<Response> for Request<State> {
451-
fn into(self) -> Response {
452-
Response::new(StatusCode::Ok).body(BufReader::new(self))
451+
fn into(mut self) -> Response {
452+
let mut res = Response::new(StatusCode::Ok);
453+
res.set_body(self.take_body());
454+
res
453455
}
454456
}
455457

0 commit comments

Comments
 (0)