Could I use tokio::select! to implement timout middleware? #875
Answered
by
davidpdrsn
goldwind-ting
asked this question in
Q&A
-
use crate::error::{Error, ErrorResp, ApiResult};
use axum::{
middleware::from_fn,
routing::get,
Router,
};
use std::net::SocketAddr;
use axum::{
http::Request,
middleware::Next,
response::Response,
};
use tokio::time;
pub async fn timeout<B>(req: Request<B>, next: Next<B>) -> ApiResult<Response> {
tokio::select! {
_ = time::sleep(time::Duration::from_secs(3)) =>{
return Err(ErrorResp::from(Error::RequestTimeout));
},
resp = next.run(req) =>{
return Ok(resp);
}
}
}
#[tokio::main]
async fn main(){
let app = Router::new()
.route("/", get(|| async {}))
.layer(from_fn(timeout));
let addr = SocketAddr::from(([127, 0, 0, 1], 5001));
tracing::info!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
} It just like above code, and is there any problem? |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Mar 20, 2022
Replies: 1 comment 1 reply
-
Looks good to me! |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
davidpdrsn
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good to me!