Skip to content

Commit aa25e97

Browse files
committed
Update Request to latest http-types
1 parent c60c37b commit aa25e97

File tree

4 files changed

+131
-64
lines changed

4 files changed

+131
-64
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ async-h1 = { version = "2.0.0", optional = true }
3636
async-sse = "2.1.0"
3737
async-std = { version = "1.6.0", features = ["unstable"] }
3838
femme = "2.0.1"
39-
http-types = "2.0.0"
39+
http-types = "2.0.1"
4040
kv-log-macro = "1.0.4"
4141
mime = "0.3.14"
4242
mime_guess = "2.0.3"

src/request.rs

Lines changed: 122 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
1-
use route_recognizer::Params;
2-
use serde::Deserialize;
3-
41
use async_std::io::{self, prelude::*, BufReader};
52
use async_std::task::{Context, Poll};
3+
use route_recognizer::Params;
64

75
use std::ops::Index;
86
use std::pin::Pin;
97
use std::{str::FromStr, sync::Arc};
108

119
use crate::cookies::CookieData;
1210
use crate::http::cookies::Cookie;
13-
use crate::http::headers::{HeaderName, HeaderValues};
11+
use crate::http::headers::{self, HeaderName, HeaderValues, ToHeaderValues};
1412
use crate::http::{self, Method, StatusCode, Url, Version};
1513
use crate::Response;
1614

@@ -114,6 +112,43 @@ impl<State> Request<State> {
114112
self.req.version()
115113
}
116114

115+
/// Get the peer socket address for the underlying transport, if
116+
/// that information is available for this request.
117+
#[must_use]
118+
pub fn peer_addr(&self) -> Option<&str> {
119+
self.req.peer_addr()
120+
}
121+
122+
/// Get the local socket address for the underlying transport, if
123+
/// that information is available for this request.
124+
#[must_use]
125+
pub fn local_addr(&self) -> Option<&str> {
126+
self.req.local_addr()
127+
}
128+
129+
/// Get the remote address for this request.
130+
///
131+
/// This is determined in the following priority:
132+
/// 1. `Forwarded` header `for` key
133+
/// 2. The first `X-Forwarded-For` header
134+
/// 3. Peer address of the transport
135+
#[must_use]
136+
pub fn remote(&self) -> Option<&str> {
137+
self.req.remote()
138+
}
139+
140+
/// Get the destination host for this request.
141+
///
142+
/// This is determined in the following priority:
143+
/// 1. `Forwarded` header `host` key
144+
/// 2. The first `X-Forwarded-Host` header
145+
/// 3. `Host` header
146+
/// 4. URL domain, if any
147+
#[must_use]
148+
pub fn host(&self) -> Option<&str> {
149+
self.req.host()
150+
}
151+
117152
/// Get an HTTP header.
118153
///
119154
/// # Examples
@@ -141,16 +176,67 @@ impl<State> Request<State> {
141176
self.req.header(key)
142177
}
143178

179+
/// Get a mutable reference to a header.
180+
pub fn header_mut(&mut self, name: impl Into<HeaderName>) -> Option<&mut HeaderValues> {
181+
self.req.header_mut(name)
182+
}
183+
184+
/// Set an HTTP header.
185+
pub fn insert_header(
186+
&mut self,
187+
name: impl Into<HeaderName>,
188+
values: impl ToHeaderValues,
189+
) -> Option<HeaderValues> {
190+
self.req.insert_header(name, values)
191+
}
192+
193+
/// Append a header to the headers.
194+
///
195+
/// Unlike `insert` this function will not override the contents of a header, but insert a
196+
/// header if there aren't any. Or else append to the existing list of headers.
197+
pub fn append_header(&mut self, name: impl Into<HeaderName>, values: impl ToHeaderValues) {
198+
self.req.append_header(name, values)
199+
}
200+
201+
/// Remove a header.
202+
pub fn remove_header(&mut self, name: impl Into<HeaderName>) -> Option<HeaderValues> {
203+
self.req.remove_header(name)
204+
}
205+
206+
/// An iterator visiting all header pairs in arbitrary order.
207+
#[must_use]
208+
pub fn iter(&self) -> headers::Iter<'_> {
209+
self.req.iter()
210+
}
211+
212+
/// An iterator visiting all header pairs in arbitrary order, with mutable references to the
213+
/// values.
214+
#[must_use]
215+
pub fn iter_mut(&mut self) -> headers::IterMut<'_> {
216+
self.req.iter_mut()
217+
}
218+
219+
/// An iterator visiting all header names in arbitrary order.
220+
#[must_use]
221+
pub fn header_names(&self) -> headers::Names<'_> {
222+
self.req.header_names()
223+
}
224+
225+
/// An iterator visiting all header values in arbitrary order.
226+
#[must_use]
227+
pub fn header_values(&self) -> headers::Values<'_> {
228+
self.req.header_values()
229+
}
230+
144231
/// Get a request extension value.
145232
#[must_use]
146233
pub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T> {
147234
self.req.ext().get()
148235
}
149236

150237
/// Set a request extension value.
151-
pub fn set_ext<T: Send + Sync + 'static>(mut self, val: T) -> Self {
152-
self.req.ext_mut().insert(val);
153-
self
238+
pub fn set_ext<T: Send + Sync + 'static>(mut self, val: T) {
239+
self.req.ext_mut().insert(val)
154240
}
155241

156242
#[must_use]
@@ -184,6 +270,11 @@ impl<State> Request<State> {
184270
.parse()
185271
}
186272

273+
/// Get the URL querystring.
274+
pub fn query<T: serde::de::DeserializeOwned>(&self) -> crate::Result<T> {
275+
self.req.query()
276+
}
277+
187278
/// Reads the entire request body into a byte buffer.
188279
///
189280
/// This method can be called after the body has already been read, but will
@@ -211,10 +302,9 @@ impl<State> Request<State> {
211302
/// #
212303
/// # Ok(()) })}
213304
/// ```
214-
pub async fn body_bytes(&mut self) -> std::io::Result<Vec<u8>> {
215-
let mut buf = Vec::with_capacity(1024);
216-
self.req.read_to_end(&mut buf).await?;
217-
Ok(buf)
305+
pub async fn body_bytes(&mut self) -> crate::Result<Vec<u8>> {
306+
let res = self.req.body_bytes().await?;
307+
Ok(res)
218308
}
219309

220310
/// Reads the entire request body into a string.
@@ -246,9 +336,9 @@ impl<State> Request<State> {
246336
/// #
247337
/// # Ok(()) })}
248338
/// ```
249-
pub async fn body_string(&mut self) -> std::io::Result<String> {
250-
let body_bytes = self.body_bytes().await?;
251-
Ok(String::from_utf8(body_bytes).map_err(|_| std::io::ErrorKind::InvalidData)?)
339+
pub async fn body_string(&mut self) -> crate::Result<String> {
340+
let res = self.req.body_string().await?;
341+
Ok(res)
252342
}
253343

254344
/// Reads and deserialized the entire request body via json.
@@ -260,36 +350,14 @@ impl<State> Request<State> {
260350
///
261351
/// If the body cannot be interpreted as valid json for the target type `T`,
262352
/// an `Err` is returned.
263-
pub async fn body_json<T: serde::de::DeserializeOwned>(&mut self) -> std::io::Result<T> {
264-
let body_bytes = self.body_bytes().await?;
265-
Ok(serde_json::from_slice(&body_bytes).map_err(|_| std::io::ErrorKind::InvalidData)?)
266-
}
267-
268-
/// Get the URL querystring.
269-
pub fn query<'de, T: Deserialize<'de>>(&'de self) -> Result<T, crate::Error> {
270-
// Default to an empty query string if no query parameter has been specified.
271-
// This allows successful deserialisation of structs where all fields are optional
272-
// when none of those fields has actually been passed by the caller.
273-
let query = self.url().query().unwrap_or("");
274-
serde_qs::from_str(query).map_err(|e| {
275-
// Return the displayable version of the deserialisation error to the caller
276-
// for easier debugging.
277-
crate::Error::from_str(StatusCode::BadRequest, format!("{}", e))
278-
})
353+
pub async fn body_json<T: serde::de::DeserializeOwned>(&mut self) -> crate::Result<T> {
354+
let res = self.req.body_json().await?;
355+
Ok(res)
279356
}
280357

281358
/// Parse the request body as a form.
282-
pub async fn body_form<T: serde::de::DeserializeOwned>(&mut self) -> io::Result<T> {
283-
let body = self
284-
.body_bytes()
285-
.await
286-
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
287-
let res = serde_qs::from_bytes(&body).map_err(|e| {
288-
std::io::Error::new(
289-
std::io::ErrorKind::Other,
290-
format!("could not decode form: {}", e),
291-
)
292-
})?;
359+
pub async fn body_form<T: serde::de::DeserializeOwned>(&mut self) -> crate::Result<T> {
360+
let res = self.req.body_form().await?;
293361
Ok(res)
294362
}
295363

@@ -300,27 +368,26 @@ impl<State> Request<State> {
300368
.and_then(|cookie_data| cookie_data.content.read().unwrap().get(name).cloned())
301369
}
302370

303-
/// Get the length of the body.
371+
/// Get the current content type
304372
#[must_use]
305-
pub fn len(&self) -> Option<usize> {
306-
self.req.len()
307-
}
308-
/// Checks if the body is empty.
309-
#[must_use]
310-
pub fn is_empty(&self) -> Option<bool> {
311-
Some(self.req.len()? == 0)
373+
pub fn content_type(&self) -> Option<http_types::Mime> {
374+
self.req.content_type()
312375
}
313376

314-
/// Peer address of the underlying transport
377+
/// Get the length of the body stream, if it has been set.
378+
///
379+
/// This value is set when passing a fixed-size object into as the body. E.g. a string, or a
380+
/// buffer. Consumers of this API should check this value to decide whether to use `Chunked`
381+
/// encoding, or set the response length.
315382
#[must_use]
316-
pub fn peer_addr(&self) -> Option<&str> {
317-
self.req.peer_addr()
383+
pub fn len(&self) -> Option<usize> {
384+
self.req.len()
318385
}
319386

320-
/// Local address of the underlying transport
387+
/// Returns `true` if the request has a set body stream length of zero, `false` otherwise.
321388
#[must_use]
322-
pub fn local_addr(&self) -> Option<&str> {
323-
self.req.local_addr()
389+
pub fn is_empty(&self) -> Option<bool> {
390+
Some(self.req.len()? == 0)
324391
}
325392
}
326393

tests/cookies.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ async fn successfully_remove_cookie() {
9191
assert_eq!(cookie.name(), COOKIE_NAME);
9292
assert_eq!(cookie.value(), "");
9393
assert_eq!(cookie.http_only(), None);
94-
assert_eq!(cookie.max_age().unwrap().num_nanoseconds(), Some(0));
94+
assert_eq!(cookie.max_age().unwrap().whole_nanoseconds(), 0);
9595
}
9696

9797
#[async_std::test]

tests/nested.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,15 @@ async fn nested() {
1919
Method::Get,
2020
Url::parse("http://example.com/foo/foo").unwrap(),
2121
);
22-
let res: Response = outer.respond(req).await.unwrap();
22+
let mut res: Response = outer.respond(req).await.unwrap();
2323
assert_eq!(res.status(), 200);
2424
assert_eq!(res.body_string().await.unwrap(), "foo");
2525

2626
let req = Request::new(
2727
Method::Get,
2828
Url::parse("http://example.com/foo/bar").unwrap(),
2929
);
30-
let res: Response = outer.respond(req).await.unwrap();
30+
let mut res: Response = outer.respond(req).await.unwrap();
3131
assert_eq!(res.status(), 200);
3232
assert_eq!(res.body_string().await.unwrap(), "bar");
3333
}
@@ -76,7 +76,7 @@ async fn nested_middleware() {
7676
Method::Get,
7777
Url::parse("http://example.com/foo/echo").unwrap(),
7878
);
79-
let res: Response = app.respond(req).await.unwrap();
79+
let mut res: Response = app.respond(req).await.unwrap();
8080
assert_eq!(res["X-Tide-Test"], "1");
8181
assert_eq!(res.status(), 200);
8282
assert_eq!(res.body_string().await.unwrap(), "/echo");
@@ -85,13 +85,13 @@ async fn nested_middleware() {
8585
Method::Get,
8686
Url::parse("http://example.com/foo/x/bar").unwrap(),
8787
);
88-
let res: Response = app.respond(req).await.unwrap();
88+
let mut res: Response = app.respond(req).await.unwrap();
8989
assert_eq!(res["X-Tide-Test"], "1");
9090
assert_eq!(res.status(), 200);
9191
assert_eq!(res.body_string().await.unwrap(), "/");
9292

9393
let req = Request::new(Method::Get, Url::parse("http://example.com/bar").unwrap());
94-
let res: Response = app.respond(req).await.unwrap();
94+
let mut res: Response = app.respond(req).await.unwrap();
9595
assert!(res.header("X-Tide-Test").is_none());
9696
assert_eq!(res.status(), 200);
9797
assert_eq!(res.body_string().await.unwrap(), "/bar");
@@ -109,12 +109,12 @@ async fn nested_with_different_state() {
109109
outer.at("/foo").nest(inner);
110110

111111
let req = Request::new(Method::Get, Url::parse("http://example.com/foo").unwrap());
112-
let res: Response = outer.respond(req).await.unwrap();
112+
let mut res: Response = outer.respond(req).await.unwrap();
113113
assert_eq!(res.status(), 200);
114114
assert_eq!(res.body_string().await.unwrap(), "the number is 42");
115115

116116
let req = Request::new(Method::Get, Url::parse("http://example.com/").unwrap());
117-
let res: Response = outer.respond(req).await.unwrap();
117+
let mut res: Response = outer.respond(req).await.unwrap();
118118
assert_eq!(res.status(), 200);
119119
assert_eq!(res.body_string().await.unwrap(), "Hello, world!");
120120
}

0 commit comments

Comments
 (0)