Skip to content

Commit

Permalink
Merge pull request #530 from jbr/populate-local-and-peer-addrs
Browse files Browse the repository at this point in the history
set local and peer addrs in tide
  • Loading branch information
yoshuawuyts authored May 23, 2020
2 parents fcd4332 + d364a95 commit 62b828c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
12 changes: 12 additions & 0 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,18 @@ impl<State> Request<State> {
pub fn is_empty(&self) -> Option<bool> {
Some(self.request.len()? == 0)
}

/// Peer address of the underlying transport
#[must_use]
pub fn peer_addr(&self) -> Option<&str> {
self.request.peer_addr()
}

/// Local address of the underlying transport
#[must_use]
pub fn local_addr(&self) -> Option<&str> {
self.request.local_addr()
}
}

impl<State> AsMut<http::Request> for Request<State> {
Expand Down
6 changes: 5 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,12 @@ impl<State: Send + Sync + 'static> Server<State> {
while let Some(stream) = incoming.next().await {
let stream = stream?;
let this = self.clone();
let local_addr = stream.local_addr().ok();
let peer_addr = stream.peer_addr().ok();
task::spawn(async move {
let res = async_h1::accept(stream, |req| async {
let res = async_h1::accept(stream, |mut req| async {
req.set_local_addr(local_addr);
req.set_peer_addr(peer_addr);
let res = this.respond(req).await;
let res = res.map_err(|_| io::Error::from(io::ErrorKind::Other))?;
Ok(res)
Expand Down
4 changes: 3 additions & 1 deletion tests/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ fn hello_world() -> Result<(), http_types::Error> {
let port = test_utils::find_port().await;
let server = task::spawn(async move {
let mut app = tide::new();
app.at("/").get(|mut req: Request<()>| async move {
app.at("/").get(move |mut req: Request<()>| async move {
assert_eq!(req.body_string().await.unwrap(), "nori".to_string());
assert!(req.local_addr().unwrap().contains(&port.to_string()));
assert!(req.peer_addr().is_some());
let res = Response::new(StatusCode::Ok).body_string("says hello".to_string());
Ok(res)
});
Expand Down

0 comments on commit 62b828c

Please sign in to comment.