Git Product home page Git Product logo

Comments (8)

Roguelazer avatar Roguelazer commented on August 17, 2024 3

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.

davidpdrsn avatar davidpdrsn commented on August 17, 2024 1

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.

xianfuxing avatar xianfuxing commented on August 17, 2024 1

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.

davidpdrsn avatar davidpdrsn commented on August 17, 2024

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.

Roguelazer avatar Roguelazer commented on August 17, 2024

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.

davidpdrsn avatar davidpdrsn commented on August 17, 2024

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.

davidpdrsn avatar davidpdrsn commented on August 17, 2024

I think I found a good solution #55. @Roguelazer wanna check it out?

from axum.

davidpdrsn avatar davidpdrsn commented on August 17, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.