Comments (8)
So I've been playing with this a bit; it does work, but accessing it from a Service (middleware layer) seems a bit hacky; here's what I have:
let remote_addr = req
.extensions()
.get::<axum::extract::ConnectInfo<SocketAddr>>()
.map(|ci| ci.0);
Can you think of any better way to get at it?
from axum.
Here is a POC:
use async_trait::async_trait;
use axum::{
extract::{FromRequest, RequestParts},
prelude::*,
AddExtension,
};
use futures_util::future::Ready;
use hyper::server::conn::AddrStream;
use std::{
convert::Infallible,
net::SocketAddr,
task::{Context, Poll},
};
use tower::{Service, ServiceBuilder};
use tower_http::add_extension::AddExtensionLayer;
#[tokio::main]
async fn main() {
let app = route(
"/",
get(|RemoteAddr(addr)| async move {
println!("`{}` connected", addr);
}),
);
hyper::Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000)))
.serve(MakeSvc(app))
.await
.unwrap();
}
struct MakeSvc<T>(T);
impl<T> Service<&AddrStream> for MakeSvc<T>
where
T: Clone,
{
type Response = AddExtension<T, RemoteAddr>;
type Error = Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, conn: &AddrStream) -> Self::Future {
let addr = conn.remote_addr();
let svc = ServiceBuilder::new()
.layer(AddExtensionLayer::new(RemoteAddr(addr)))
.service(self.0.clone());
futures_util::future::ok(svc)
}
}
#[derive(Clone, Copy)]
struct RemoteAddr(SocketAddr);
#[async_trait]
impl<B> FromRequest<B> for RemoteAddr
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let addr = req
.extensions()
.expect("extensions taken by other extractor")
.get::<RemoteAddr>()
.copied()
.expect("`RemoteAddr` extension missing");
Ok(addr)
}
}
It'll require a 0.2 since we have to change the return type of RoutingDsl::into_make_service
so I think we should wait a bit and see if other breaking changes become necessary.
from axum.
So I've been playing with this a bit; it does work, but accessing it from a Service (middleware layer) seems a bit hacky; here's what I have:
let remote_addr = req .extensions() .get::<axum::extract::ConnectInfo<SocketAddr>>() .map(|ci| ci.0);Can you think of any better way to get at it?
works for me.
from axum.
Makes sense to provide!
Without having through about this too much it might be possible to change RoutingDsl::into_make_service
to return some custom service that stores the remote address in a request extension, which can be picked up by an extractor.
from axum.
I guess the only thing to make sure is that it's okay to use AddrStream
as the concrete type there (e.g., if someone wants to use Hyper with domain sockets or another kind of Stream
that doesn't have a SocketAddress, what happens?).
from axum.
Right. Hyper does have https://docs.rs/hyper/0.14.11/hyper/server/accept/trait.Accept.html so it might require being generic over that.
from axum.
I think I found a good solution #55. @Roguelazer wanna check it out?
from axum.
Doesn't seem hacky to me. Its literally how the ConnectInfo
extractor works https://github.com/tokio-rs/axum/blob/main/src/extract/connect_info.rs#L125.
from axum.
Related Issues (20)
- 0.7.5 can't get headerMap and body in one handler?
- Remove `heck` from axum-macros HOT 2
- Cors error to return bytes of file
- Unexpected behaviour in example `static-file-server`
- there is no timer running, must be called from the context of Tokio runtime HOT 1
- Report error: "implementation of `std::marker::Send` is not general enough" in route handler HOT 1
- stream-to-file can not upload big file HOT 1
- `FromRef` triggers `clippy::clone_of_ref_ptr` HOT 1
- Content-Type for Json does not support those of aws HOT 1
- axum fails tests without default features, due to incompletely declared feature "json" HOT 5
- Conversion from BodyDataStream to AsyncRead is not working HOT 3
- `RequestBodyLimit` docs link out of date HOT 1
- feat: expose inner `WebSocketStream`
- Weird behavior when returning response without consuming multipart body [REPRO] HOT 2
- Handler<_, _>` is not satisfied the following other types implement trait `Handler<T, S>`: HOT 7
- Example for low-level-native-tls HOT 5
- How can I set `max_concurrent_streams` HOT 1
- 0.7.5. server not reachable
- Drop IntoResponse trait requirement from FromRequestParts and FromRequest Rejections HOT 1
- Duplicate dependency `sync_wrapper` with latest version of `axum` and `axum-core`
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from axum.