Skip to main content

Handle

Struct Handle 

Source
pub struct Handle<A: Address> { /* private fields */ }
Expand description

A handle for Server.

It controls the server it is passed to and, through with_control, any number of servers sharing the same Control.

Implementations§

Source§

impl<A: Address> Handle<A>

Source

pub fn new() -> Self

Create a new handle.

Examples found in repository?
examples/shutdown.rs (line 16)
13async fn main() {
14    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
15
16    let handle = Handle::new();
17
18    // Spawn a task to shutdown server.
19    tokio::spawn(shutdown(handle.clone()));
20
21    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
22    println!("listening on {}", addr);
23    axum_server::bind(addr)
24        .handle(handle)
25        .serve(app.into_make_service())
26        .await
27        .unwrap();
28
29    println!("server is shut down");
30}
More examples
Hide additional examples
examples/graceful_shutdown.rs (line 19)
16async fn main() {
17    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
18
19    let handle = Handle::new();
20
21    // Spawn a task to gracefully shutdown server.
22    tokio::spawn(graceful_shutdown(handle.clone()));
23
24    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
25    println!("listening on {}", addr);
26    axum_server::bind(addr)
27        .handle(handle)
28        .serve(app.into_make_service())
29        .await
30        .unwrap();
31
32    println!("server is shut down");
33}
Source

pub fn with_control(control: Control) -> Self

Create a handle that shares shutdown and connection counting with control.

Each server should get its own Handle so that listening reports the address of that server.

Examples found in repository?
examples/multiple_listeners.rs (line 14)
7async fn main() -> io::Result<()> {
8    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
9
10    // One control handle drains every listener below.
11    let control = Control::new();
12    let mut servers = JoinSet::new();
13
14    let tcp_handle = Handle::<SocketAddr>::with_control(control.clone());
15    let tcp =
16        axum_server::bind(SocketAddr::from(([127, 0, 0, 1], 3000))).handle(tcp_handle.clone());
17    let tcp_service = app.clone().into_make_service();
18
19    servers.spawn(async move { tcp.serve(tcp_service).await });
20
21    #[cfg(unix)]
22    let unix_handle = {
23        use std::os::unix::net::SocketAddr;
24
25        let path = std::env::temp_dir().join("axum-server-multiple-listeners.sock");
26        let _ = std::fs::remove_file(&path);
27
28        let handle = Handle::with_control(control.clone());
29        let unix = axum_server::bind(SocketAddr::from_pathname(path)?).handle(handle.clone());
30        let service = app.clone().into_make_service();
31
32        servers.spawn(async move { unix.serve(service).await });
33
34        handle
35    };
36
37    println!("tcp: http://{}/", tcp_handle.listening().await.unwrap());
38    #[cfg(unix)]
39    println!(
40        "unix: {:?}",
41        unix_handle
42            .listening()
43            .await
44            .unwrap()
45            .as_pathname()
46            .unwrap()
47    );
48
49    let shutdown = control.clone();
50    tokio::spawn(async move {
51        let _ = tokio::signal::ctrl_c().await;
52        shutdown.graceful_shutdown(Some(Duration::from_secs(10)));
53    });
54
55    // A failing listener stops the others instead of leaving them running.
56    while let Some(result) = servers.join_next().await {
57        match result {
58            Ok(Ok(())) => {}
59            Ok(Err(error)) => {
60                eprintln!("server error: {error}");
61                control.shutdown();
62            }
63            Err(error) => {
64                eprintln!("server task failed: {error}");
65                control.shutdown();
66            }
67        }
68    }
69
70    #[cfg(unix)]
71    let _ = std::fs::remove_file(std::env::temp_dir().join("axum-server-multiple-listeners.sock"));
72
73    Ok(())
74}
Source

pub fn control(&self) -> Control

Get the shared Control.

Source

pub fn connection_count(&self) -> usize

Get the number of connections.

Examples found in repository?
examples/graceful_shutdown.rs (line 48)
35async fn graceful_shutdown(handle: Handle<SocketAddr>) {
36    // Wait 10 seconds.
37    sleep(Duration::from_secs(10)).await;
38
39    println!("sending graceful shutdown signal");
40
41    // Signal the server to shutdown using Handle.
42    handle.graceful_shutdown(Some(Duration::from_secs(30)));
43
44    // Print alive connection count every second.
45    loop {
46        sleep(Duration::from_secs(1)).await;
47
48        println!("alive connections: {}", handle.connection_count());
49    }
50}
Source

pub fn shutdown(&self)

Shutdown the server.

Examples found in repository?
examples/shutdown.rs (line 39)
32async fn shutdown(handle: Handle<SocketAddr>) {
33    // Wait 20 seconds.
34    sleep(Duration::from_secs(20)).await;
35
36    println!("sending shutdown signal");
37
38    // Signal the server to shutdown using Handle.
39    handle.shutdown();
40}
Source

pub fn graceful_shutdown(&self, duration: Option<Duration>)

Gracefully shutdown the server.

None means indefinite grace period.

Examples found in repository?
examples/graceful_shutdown.rs (line 42)
35async fn graceful_shutdown(handle: Handle<SocketAddr>) {
36    // Wait 10 seconds.
37    sleep(Duration::from_secs(10)).await;
38
39    println!("sending graceful shutdown signal");
40
41    // Signal the server to shutdown using Handle.
42    handle.graceful_shutdown(Some(Duration::from_secs(30)));
43
44    // Print alive connection count every second.
45    loop {
46        sleep(Duration::from_secs(1)).await;
47
48        println!("alive connections: {}", handle.connection_count());
49    }
50}
Source

pub async fn listening(&self) -> Option<A>

Returns local address and port when server starts listening.

Returns None if server fails to bind.

Examples found in repository?
examples/multiple_listeners.rs (line 37)
7async fn main() -> io::Result<()> {
8    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
9
10    // One control handle drains every listener below.
11    let control = Control::new();
12    let mut servers = JoinSet::new();
13
14    let tcp_handle = Handle::<SocketAddr>::with_control(control.clone());
15    let tcp =
16        axum_server::bind(SocketAddr::from(([127, 0, 0, 1], 3000))).handle(tcp_handle.clone());
17    let tcp_service = app.clone().into_make_service();
18
19    servers.spawn(async move { tcp.serve(tcp_service).await });
20
21    #[cfg(unix)]
22    let unix_handle = {
23        use std::os::unix::net::SocketAddr;
24
25        let path = std::env::temp_dir().join("axum-server-multiple-listeners.sock");
26        let _ = std::fs::remove_file(&path);
27
28        let handle = Handle::with_control(control.clone());
29        let unix = axum_server::bind(SocketAddr::from_pathname(path)?).handle(handle.clone());
30        let service = app.clone().into_make_service();
31
32        servers.spawn(async move { unix.serve(service).await });
33
34        handle
35    };
36
37    println!("tcp: http://{}/", tcp_handle.listening().await.unwrap());
38    #[cfg(unix)]
39    println!(
40        "unix: {:?}",
41        unix_handle
42            .listening()
43            .await
44            .unwrap()
45            .as_pathname()
46            .unwrap()
47    );
48
49    let shutdown = control.clone();
50    tokio::spawn(async move {
51        let _ = tokio::signal::ctrl_c().await;
52        shutdown.graceful_shutdown(Some(Duration::from_secs(10)));
53    });
54
55    // A failing listener stops the others instead of leaving them running.
56    while let Some(result) = servers.join_next().await {
57        match result {
58            Ok(Ok(())) => {}
59            Ok(Err(error)) => {
60                eprintln!("server error: {error}");
61                control.shutdown();
62            }
63            Err(error) => {
64                eprintln!("server task failed: {error}");
65                control.shutdown();
66            }
67        }
68    }
69
70    #[cfg(unix)]
71    let _ = std::fs::remove_file(std::env::temp_dir().join("axum-server-multiple-listeners.sock"));
72
73    Ok(())
74}

Trait Implementations§

Source§

impl<A: Clone + Address> Clone for Handle<A>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<A: Debug + Address> Debug for Handle<A>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<A: Address> Default for Handle<A>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<A> Forget for Handle<A>

§

impl<A> Freeze for Handle<A>
where Arc<AddrSlot<A>>: Freeze,

§

impl<A> RefUnwindSafe for Handle<A>
where Arc<AddrSlot<A>>: RefUnwindSafe,

§

impl<A> Send for Handle<A>
where Arc<AddrSlot<A>>: Send,

§

impl<A> Sync for Handle<A>
where Arc<AddrSlot<A>>: Sync,

§

impl<A> Unpin for Handle<A>
where Arc<AddrSlot<A>>: Unpin,

§

impl<A> UnsafeUnpin for Handle<A>
where Arc<AddrSlot<A>>: UnsafeUnpin,

§

impl<A> UnwindSafe for Handle<A>
where Arc<AddrSlot<A>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more