Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bring response in line with http-types #562

Merged
merged 6 commits into from
Jun 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions examples/chunked.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use async_std::fs;
use async_std::io::BufReader;
use async_std::task;
use tide::{Response, StatusCode};
use tide::{Body, Response, StatusCode};

fn main() -> Result<(), std::io::Error> {
task::block_on(async {
let mut app = tide::new();
app.at("/").get(|_| async move {
let file = fs::File::open(file!()).await.unwrap();
let res = Response::new(StatusCode::Ok).body(BufReader::new(file));
let mut res = Response::new(StatusCode::Ok);
res.set_body(Body::from_file(file!()).await.unwrap());
Ok(res)
});
app.listen("127.0.0.1:8080").await?;
Expand Down
6 changes: 3 additions & 3 deletions examples/cookies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ async fn retrieve_cookie(cx: Request<()>) -> tide::Result<String> {
Ok(format!("hello cookies: {:?}", cx.cookie("hello").unwrap()))
}

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

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

app.at("/").get(retrieve_cookie);
app.at("/set").get(set_cookie);
app.at("/set").get(insert_cookie);
app.at("/remove").get(remove_cookie);
app.listen("127.0.0.1:8080").await?;

Expand Down
13 changes: 6 additions & 7 deletions examples/graphql.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use async_std::task;
use juniper::RootNode;
use std::sync::RwLock;
use tide::{Redirect, Request, Response, Server, StatusCode};
use tide::{Body, Redirect, Request, Response, Server, StatusCode};

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

let res = Response::new(status)
.body_json(&response)
.expect("be able to serialize the graphql response");
let mut res = Response::new(status);
res.set_body(Body::from_json(&response)?);
Ok(res)
}

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

Expand Down
6 changes: 4 additions & 2 deletions examples/json.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use async_std::task;
use serde::{Deserialize, Serialize};
use tide::prelude::*;
use tide::{Request, Response, StatusCode};
use tide::{Body, Request, Response};

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

Ok(Response::new(StatusCode::Ok).body_json(&cat)?)
let mut res = Response::new(200);
res.set_body(Body::from_json(&cat)?);
Ok(res)
});

app.at("/animals").get(|_| async {
Expand Down
27 changes: 16 additions & 11 deletions examples/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tide::http::mime;
use tide::{After, Before, Middleware, Next, Request, Response, Result, StatusCode};

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

let mut response = next.run(req).await?;
let mut res = next.run(req).await?;

response = response.set_header("request-number", count.to_string());
Ok(response)
res.insert_header("request-number", count.to_string());
Ok(res)
})
}
}
Expand Down Expand Up @@ -101,14 +102,18 @@ async fn main() -> Result<()> {
app.middleware(After(|result: Result| async move {
let response = result.unwrap_or_else(|e| Response::new(e.status()));
match response.status() {
StatusCode::NotFound => Ok(response
.set_content_type(tide::http::mime::HTML)
.body_string(NOT_FOUND_HTML_PAGE.into())),

StatusCode::InternalServerError => Ok(response
.set_content_type(tide::http::mime::HTML)
.body_string(INTERNAL_SERVER_ERROR_HTML_PAGE.into())),

StatusCode::NotFound => {
let mut res = Response::new(404);
res.set_content_type(mime::HTML);
res.set_body(NOT_FOUND_HTML_PAGE);
Ok(res)
}
StatusCode::InternalServerError => {
let mut res = Response::new(500);
res.set_content_type(mime::HTML);
res.set_body(INTERNAL_SERVER_ERROR_HTML_PAGE);
Ok(res)
}
_ => Ok(response),
}
}));
Expand Down
4 changes: 2 additions & 2 deletions src/cookies/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use std::sync::{Arc, RwLock};
/// app.at("/get").get(|cx: Request<()>| async move { Ok(cx.cookie("testCookie").unwrap().value().to_string()) });
/// app.at("/set").get(|_| async {
/// let mut res = Response::new(StatusCode::Ok);
/// res.set_cookie(Cookie::new("testCookie", "NewCookieValue"));
/// res.insert_cookie(Cookie::new("testCookie", "NewCookieValue"));
/// Ok(res)
/// });
/// ```
Expand Down Expand Up @@ -69,7 +69,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
// iterate over added and removed cookies
for cookie in jar.delta() {
let encoded_cookie = cookie.encoded().to_string();
res = res.append_header(headers::SET_COOKIE, encoded_cookie);
res.append_header(headers::SET_COOKIE, encoded_cookie);
}
Ok(res)
})
Expand Down
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
//! ```no_run
//! # use async_std::task::block_on;
//! # fn main() -> Result<(), std::io::Error> { block_on(async {
//! # use tide::{Request, Response};
//! # use tide::{Body, Request, Response};
//! #
//! #[derive(Debug, serde::Deserialize, serde::Serialize)]
//! struct Counter { count: usize }
Expand All @@ -61,7 +61,9 @@
//! let mut counter: Counter = req.body_json().await?;
//! println!("count is {}", counter.count);
//! counter.count += 1;
//! Ok(Response::new(tide::http::StatusCode::Ok).body_json(&counter)?)
//! let mut res = Response::new(200);
//! res.set_body(Body::from_json(&counter)?);
//! Ok(res)
//! });
//! app.listen("127.0.0.1:8080").await?;
//! #
Expand Down
4 changes: 3 additions & 1 deletion src/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ impl<T: AsRef<str>> Into<Response> for Redirect<T> {

impl<T: AsRef<str>> Into<Response> for &Redirect<T> {
fn into(self) -> Response {
Response::new(self.status).set_header(LOCATION, self.location.as_ref())
let mut res = Response::new(self.status);
res.insert_header(LOCATION, self.location.as_ref());
res
}
}
8 changes: 5 additions & 3 deletions src/request.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use async_std::io::{self, prelude::*, BufReader};
use async_std::io::{self, prelude::*};
use async_std::task::{Context, Poll};
use route_recognizer::Params;

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

Expand Down
Loading