Skip to main content

timeouts/
timeouts.rs

1//! Run with `cargo run --example timeouts` command.
2//!
3//! Demonstrates the connection and request timeouts:
4//!
5//! - `first_request_timeout` closes a new connection if no request arrives in
6//!   time, including while hyper is detecting the HTTP protocol.
7//! - `header_read_timeout` bounds reading the headers of a request.
8//! - `keep_alive_interval` and `keep_alive_timeout` bound idle HTTP/2
9//!   connections.
10//!
11//! For TLS, `RustlsAcceptor::handshake_timeout` and
12//! `OpenSSLAcceptor::handshake_timeout` bound the TLS handshake.
13
14use axum::{routing::get, Router};
15use axum_server::Server;
16use std::{net::SocketAddr, time::Duration};
17
18#[tokio::main]
19async fn main() {
20    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
21
22    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
23
24    let mut server = Server::bind(addr).first_request_timeout(Duration::from_secs(10));
25
26    let mut http1 = server.http_builder().http1();
27    http1.header_read_timeout(Duration::from_secs(10));
28
29    let mut http2 = server.http_builder().http2();
30    http2.keep_alive_interval(Duration::from_secs(30));
31    http2.keep_alive_timeout(Duration::from_secs(10));
32
33    println!("listening on {addr}");
34    server.serve(app.into_make_service()).await.unwrap();
35}