Middleware that provides support for request timeouts.
In web services, some requests might take too long to process due to various reasons (e.g., slow database queries, slow responses from external services). To prevent these long-running requests from consuming server resources and affecting the processing of other requests, you can use timeout middleware to set a maximum processing time limit for requests. If this time limit is exceeded, the request will be automatically interrupted, and a timeout error will be returned.
Example Code
In the example above, we created two handler functions: fast
, which responds quickly, and slow
, which delays for 6 seconds before responding. Timeout::new(Duration::from_secs(5))
sets a 5-second timeout limit for all requests. When accessing the /slow
path, the request will time out because its processing time exceeds the 5-second limit. Conversely, when accessing the /fast
path, the request will be processed normally and return a result.