Skip to content

Commit

Permalink
Merge pull request #520 from jbr/update-http-types
Browse files Browse the repository at this point in the history
http-types and async-h1 2.0.0
  • Loading branch information
yoshuawuyts authored May 22, 2020
2 parents d241f21 + 1e0be8b commit 204268a
Show file tree
Hide file tree
Showing 16 changed files with 198 additions and 318 deletions.
11 changes: 5 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,11 @@ unstable = []
__internal__bench = []

[dependencies]
async-h1 = { version = "1.1.2", optional = true }
async-h1 = { version = "2.0.0", optional = true }
async-sse = "2.1.0"
async-std = { version = "1.4.0", features = ["unstable"] }
cookie = { version = "0.12.0", features = ["percent-encode"]}
async-std = { version = "1.6.0", features = ["unstable"] }
femme = "2.0.1"
http-types = "1.0.1"
http-types = "2.0.0"
kv-log-macro = "1.0.4"
mime = "0.3.14"
mime_guess = "2.0.3"
Expand All @@ -47,12 +46,12 @@ serde_json = "1.0.41"
serde_qs = "0.5.0"

[dev-dependencies]
async-std = { version = "1.4.0", features = ["unstable", "attributes"] }
async-std = { version = "1.6.0", features = ["unstable", "attributes"] }
juniper = "0.14.1"
portpicker = "0.1.0"
serde = { version = "1.0.102", features = ["derive"] }
surf = "2.0.0-alpha.1"
criterion = "0.3.1"
surf = { version = "2.0.0-alpha.2", default-features = false, features = ["h1-client"] }

[[test]]
name = "nested"
Expand Down
2 changes: 1 addition & 1 deletion examples/graphql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async fn handle_graphql(mut cx: Request<State>) -> tide::Result {
async fn handle_graphiql(_: Request<State>) -> tide::Result {
let res = Response::new(StatusCode::Ok)
.body_string(juniper::http::graphiql::graphiql_source("/graphql"))
.set_header("content-type".parse().unwrap(), "text/html;charset=utf-8");
.set_mime(mime::TEXT_HTML_UTF_8);
Ok(res)
}

Expand Down
9 changes: 5 additions & 4 deletions src/cookies/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ use std::sync::{Arc, RwLock};
///
/// ```
/// # use tide::{Request, Response, StatusCode};
/// # use tide::http::cookies::Cookie;
/// let mut app = tide::Server::new();
/// 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::Cookie::new("testCookie", "NewCookieValue"));
/// res.set_cookie(Cookie::new("testCookie", "NewCookieValue"));
/// Ok(res)
/// });
/// ```
Expand All @@ -38,13 +39,13 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
next: Next<'a, State>,
) -> BoxFuture<'a, crate::Result> {
Box::pin(async move {
let cookie_jar = if let Some(cookie_data) = ctx.local::<CookieData>() {
let cookie_jar = if let Some(cookie_data) = ctx.ext::<CookieData>() {
cookie_data.content.clone()
} else {
let cookie_data = CookieData::from_request(&ctx);
// no cookie data in local context, so we try to create it
// no cookie data in ext context, so we try to create it
let content = cookie_data.content.clone();
ctx = ctx.set_local(cookie_data);
ctx = ctx.set_ext(cookie_data);
content
};

Expand Down
3 changes: 2 additions & 1 deletion src/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
//! # Ok(()) }) }
//! ```
use crate::http::headers::LOCATION;
use crate::utils::BoxFuture;
use crate::StatusCode;
use crate::{Endpoint, Request, Response};
Expand Down Expand Up @@ -103,6 +104,6 @@ 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".parse().unwrap(), &self.location)
Response::new(self.status).set_header(LOCATION, self.location.as_ref())
}
}
32 changes: 15 additions & 17 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{str::FromStr, sync::Arc};

use crate::cookies::CookieData;
use crate::http::cookies::Cookie;
use crate::http::headers::{HeaderName, HeaderValue};
use crate::http::headers::{HeaderName, HeaderValues};
use crate::http::{self, Method, StatusCode, Url, Version};
use crate::Response;

Expand Down Expand Up @@ -124,7 +124,7 @@ impl<State> Request<State> {
///
/// let mut app = tide::new();
/// app.at("/").get(|req: Request<()>| async move {
/// assert_eq!(req.header(&"X-Forwarded-For".parse().unwrap()), Some(&vec!["127.0.0.1".parse().unwrap()]));
/// assert_eq!(req.header("X-Forwarded-For").unwrap(), "127.0.0.1");
/// Ok("")
/// });
/// app.listen("127.0.0.1:8080").await?;
Expand All @@ -134,20 +134,20 @@ impl<State> Request<State> {
#[must_use]
pub fn header(
&self,
key: &http_types::headers::HeaderName,
) -> Option<&Vec<http_types::headers::HeaderValue>> {
key: impl Into<http_types::headers::HeaderName>,
) -> Option<&http_types::headers::HeaderValues> {
self.request.header(key)
}

/// Get a local value.
/// Get a request extension value.
#[must_use]
pub fn local<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.request.local().get()
pub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.request.ext().get()
}

/// Set a local value.
pub fn set_local<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.request.local_mut().insert(val);
/// Set a request extension value.
pub fn set_ext<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.request.ext_mut().insert(val);
self
}

Expand Down Expand Up @@ -294,10 +294,8 @@ impl<State> Request<State> {
/// returns a `Cookie` by name of the cookie.
#[must_use]
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
if let Some(cookie_data) = self.local::<CookieData>() {
return cookie_data.content.read().unwrap().get(name).cloned();
}
None
self.ext::<CookieData>()
.and_then(|cookie_data| cookie_data.content.read().unwrap().get(name).cloned())
}

/// Get the length of the body.
Expand Down Expand Up @@ -349,7 +347,7 @@ impl<State: Send + Sync + 'static> Into<Response> for Request<State> {
}

impl<State> IntoIterator for Request<State> {
type Item = (HeaderName, Vec<HeaderValue>);
type Item = (HeaderName, HeaderValues);
type IntoIter = http_types::headers::IntoIter;

/// Returns a iterator of references over the remaining items.
Expand All @@ -360,7 +358,7 @@ impl<State> IntoIterator for Request<State> {
}

impl<'a, State> IntoIterator for &'a Request<State> {
type Item = (&'a HeaderName, &'a Vec<HeaderValue>);
type Item = (&'a HeaderName, &'a HeaderValues);
type IntoIter = http_types::headers::Iter<'a>;

#[inline]
Expand All @@ -370,7 +368,7 @@ impl<'a, State> IntoIterator for &'a Request<State> {
}

impl<'a, State> IntoIterator for &'a mut Request<State> {
type Item = (&'a HeaderName, &'a mut Vec<HeaderValue>);
type Item = (&'a HeaderName, &'a mut HeaderValues);
type IntoIter = http_types::headers::IterMut<'a>;

#[inline]
Expand Down
48 changes: 17 additions & 31 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use mime::Mime;
use serde::Serialize;

use crate::http::cookies::Cookie;
use crate::http::headers::{HeaderName, HeaderValue};
use crate::http::headers::{HeaderName, HeaderValues, ToHeaderValues, CONTENT_TYPE};
use crate::http::{self, Body, StatusCode};
use crate::Redirect;
use crate::redirect::Redirect;

#[derive(Debug)]
pub(crate) enum CookieEvent {
Expand Down Expand Up @@ -99,38 +99,24 @@ impl Response {

/// Get an HTTP header.
#[must_use]
pub fn header(&self, name: &HeaderName) -> Option<&Vec<HeaderValue>> {
pub fn header(&self, name: impl Into<HeaderName>) -> Option<&HeaderValues> {
self.res.header(name)
}

/// Remove a header.
pub fn remove_header(&mut self, name: &HeaderName) -> Option<Vec<HeaderValue>> {
pub fn remove_header(&mut self, name: impl Into<HeaderName>) -> Option<HeaderValues> {
self.res.remove_header(name)
}

/// Insert an HTTP header.
pub fn set_header(
mut self,
key: http_types::headers::HeaderName,
value: impl AsRef<str>,
) -> Self {
let value = value.as_ref().to_owned();
self.res
.insert_header(key, &[value.parse().unwrap()][..])
.expect("invalid header");
pub fn set_header(mut self, key: impl Into<HeaderName>, value: impl ToHeaderValues) -> Self {
self.res.insert_header(key, value);
self
}

/// Append an HTTP header.
pub fn append_header(
mut self,
key: http_types::headers::HeaderName,
value: impl AsRef<str>,
) -> Self {
let value = value.as_ref().to_owned();
self.res
.append_header(key, &[value.parse().unwrap()][..])
.expect("invalid header");
pub fn append_header(mut self, key: impl Into<HeaderName>, value: impl ToHeaderValues) -> Self {
self.res.append_header(key, value);
self
}

Expand All @@ -139,7 +125,7 @@ impl Response {
/// [Read more on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)
#[must_use]
pub fn set_mime(self, mime: Mime) -> Self {
self.set_header(http_types::headers::CONTENT_TYPE, format!("{}", mime))
self.set_header(CONTENT_TYPE, mime.to_string())
}

/// Pass a string as the request body.
Expand Down Expand Up @@ -233,15 +219,15 @@ impl Response {
self.cookie_events.push(CookieEvent::Removed(cookie));
}

/// Get a local value.
/// Get a response extension value.
#[must_use]
pub fn local<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.res.local().get()
pub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.res.ext().get()
}

/// Set a local value.
pub fn set_local<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.res.local_mut().insert(val);
pub fn set_ext<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.res.ext_mut().insert(val);
self
}

Expand Down Expand Up @@ -309,7 +295,7 @@ impl<'a> From<&'a str> for Response {
}

impl IntoIterator for Response {
type Item = (HeaderName, Vec<HeaderValue>);
type Item = (HeaderName, HeaderValues);
type IntoIter = http_types::headers::IntoIter;

/// Returns a iterator of references over the remaining items.
Expand All @@ -320,7 +306,7 @@ impl IntoIterator for Response {
}

impl<'a> IntoIterator for &'a Response {
type Item = (&'a HeaderName, &'a Vec<HeaderValue>);
type Item = (&'a HeaderName, &'a HeaderValues);
type IntoIter = http_types::headers::Iter<'a>;

#[inline]
Expand All @@ -330,7 +316,7 @@ impl<'a> IntoIterator for &'a Response {
}

impl<'a> IntoIterator for &'a mut Response {
type Item = (&'a HeaderName, &'a mut Vec<HeaderValue>);
type Item = (&'a HeaderName, &'a mut HeaderValues);
type IntoIter = http_types::headers::IterMut<'a>;

#[inline]
Expand Down
2 changes: 1 addition & 1 deletion src/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl<'a, State: 'static> Route<'a, State> {
));
(ep.clone(), ep)
};
self.router.add(&self.path, method.clone(), ep1);
self.router.add(&self.path, method, ep1);
let wildcard = self.at("*--tide-path-rest");
wildcard.router.add(&wildcard.path, method, ep2);
} else {
Expand Down
Loading

0 comments on commit 204268a

Please sign in to comment.