shuttle_axum/
lib.rs

1#![doc = include_str!("../README.md")]
2use shuttle_runtime::{CustomError, Error};
3use std::net::SocketAddr;
4
5#[cfg(feature = "axum")]
6pub use axum;
7#[cfg(feature = "axum-0-7")]
8pub use axum_0_7 as axum;
9
10#[cfg(feature = "axum")]
11use axum::Router;
12#[cfg(feature = "axum-0-7")]
13use axum_0_7::Router;
14
15/// A wrapper type for [axum::Router] so we can implement [shuttle_runtime::Service] for it.
16pub struct AxumService(pub Router);
17
18#[shuttle_runtime::async_trait]
19impl shuttle_runtime::Service for AxumService {
20    /// Takes the router that is returned by the user in their [shuttle_runtime::main] function
21    /// and binds to an address passed in by shuttle.
22    async fn bind(mut self, addr: SocketAddr) -> Result<(), Error> {
23        #[cfg(feature = "axum")]
24        axum::serve(
25            shuttle_runtime::tokio::net::TcpListener::bind(addr)
26                .await
27                .map_err(CustomError::new)?,
28            self.0,
29        )
30        .await
31        .map_err(CustomError::new)?;
32        #[cfg(feature = "axum-0-7")]
33        axum_0_7::serve(
34            shuttle_runtime::tokio::net::TcpListener::bind(addr)
35                .await
36                .map_err(CustomError::new)?,
37            self.0,
38        )
39        .await
40        .map_err(CustomError::new)?;
41
42        Ok(())
43    }
44}
45
46impl From<Router> for AxumService {
47    fn from(router: Router) -> Self {
48        Self(router)
49    }
50}
51
52#[doc = include_str!("../README.md")]
53pub type ShuttleAxum = Result<AxumService, Error>;