Timeout Middleware
Provides middleware support for timeout handling.
Use Cases
In web services, certain requests may take too long to process due to various reasons (such as slow database queries, delayed external service responses, etc.). To prevent these long-running requests from consuming server resources and affecting the processing of other requests, a timeout middleware can be used to set a maximum processing time limit for requests. If this time limit is exceeded, the request will be automatically terminated, and a timeout error will be returned.
Example Code
In the example above, we created two handler functions: a fast-responding fast and a slow that delays for 6 seconds before responding. A timeout limit of 5 seconds is set for all requests using Timeout::new(Duration::from_secs(5)). When accessing the /slow path, the request will time out because the processing time exceeds the 5-second limit. In contrast, when accessing the /fast path, the request will be processed normally and return a result.