use pavex::{middleware::Next, response::Response};
use std::future::IntoFuture;
use tokio::time::{timeout, error::Elapsed};
pub async fn timeout_middleware<C>(
// A handle on the rest of the processing pipeline for the incoming
// request.
//
// Middlewares can choose to short-circuit the execution (i.e.
// return an error and abort the processing) or perform some
// computation and then delegate to `next` by awaiting it.
//
// All middlewares in Pavex *must* take `Next<_>` as an input.
next: Next<C>,
// Middlewares can take advantage of dependency injection!
// You just list what inputs you need and the framework will provide them
// (if possible, or return a nice error at *compile-time* if not).
//
// `TimeoutConfig` could be defined at start-up time, sharing the same
// value for all routes, or it could be customised at runtime on a
// per-request basis (e.g. to provide a configurable quality of service
// depending on the pricing plan of the client issueing the request).
// `timeout_middleware` doesn't care how or when `TimeoutConfig`
// gets computed.
// Happy decoupling!
config: TimeoutConfig
) -> Result<Response, Elapsed>
where
C: IntoFuture<Output = Response>
{
timeout(config.request_timeout, next.into_future()).await
}
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。