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

set local and peer addrs in tide #530

Merged
merged 2 commits into from
May 23, 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
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