Detect connection closed inside POST handler doing long-poll or SSE #1094
-
Thank you for writing Axum, I am amazed by it's power and comprehensiveness. I am writing a POST handler which is blocking on a future for an undetermined amount of time. I'd this handler to give-up and return if the originator goes away, ie: terminates the HTTP request or closes the TCP socket. I am currently using ContentLengthLimit to get the request body. I was thinking maybe I could use BodyStream or RawBody to detect a closed connection, Is there a way I can pass a future into my handler somehow that I can use to detect a closed connection Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Happy to hear you're enjoying axum 😊 If I understand you correctly you don't actually need to do anything. It works automatically thanks to async rust and hyper. If the client closes the connection before the server sends a response, hyper will stop calling use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler() {
// this will go out of scope either when this function returns (which it never does)
// or hyper drops the future because the client closed the connection
let _guard = Guard;
// wait forever
std::future::pending::<()>().await
}
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
println!("a `Guard` was dropped!")
}
} Try calling All this is unrelated to |
Beta Was this translation helpful? Give feedback.
Happy to hear you're enjoying axum 😊
If I understand you correctly you don't actually need to do anything. It works automatically thanks to async rust and hyper. If the client closes the connection before the server sends a response, hyper will stop calling
poll
and drop the response future. That can be demonstrated by doing something like this: