ConnectInfo
extractor no longer accepted in middleware::from_fn_with_state
#2369
Answered
by
davidpdrsn
leonardoarcari
asked this question in
Q&A
-
Bug ReportVersion
PlatformWindows 11 x64 DescriptionStarting from Axum v0.7, I can no longer extract let app = Router::new()
.route("/", get(|| async { "Hello World!" }))
.route_layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(middleware::from_fn_with_state(
ctx.clone(),
requests_stats,
))
)
.with_state(ctx.clone())
.into_make_service_with_connect_info();
pub async fn requests_stats(
State(state): State<AppContext>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
req: Request,
next: Next,
) -> Result<Response> {
/* middlware body */
} Fails with the following error:
Removing Let me know if you need additional information. Cheers! 🙇 |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Nov 29, 2023
Replies: 1 comment 4 replies
-
Works fine for me use std::net::SocketAddr;
use axum::{
extract::{ConnectInfo, Request, State},
middleware::{from_fn_with_state, Next},
response::Response,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello World!" }))
.route_layer(from_fn_with_state("state", requests_stats))
.into_make_service_with_connect_info::<SocketAddr>();
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
pub async fn requests_stats(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
State(state): State<&'static str>,
req: Request,
next: Next,
) -> Response {
dbg!(addr);
dbg!(state);
next.run(req).await
} I see this in the console when sending a request
|
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah yes that makes sense.
Request<Body>
is not!Sync
(because as you sayBody
is!Sync
). That means&Request<Body>
is!Send
meaning the future returned byrecord_visitors_stats
is also!Send
and that makes it not compile. So you'll have to pass the headers directly.The reason
Body
is!Sync
is that you can't really do anything with&Body
from multiple threads since streaming it requires a&mut Body
(or rather aPin<&mut Body>
). So therefore streams are normally not!Sync
. Another example of this isBoxStream
from futures.