2024-06-26 10:20:52 +02:00
|
|
|
use {
|
2024-08-19 16:43:31 +02:00
|
|
|
axum::{
|
2025-03-07 18:21:23 +01:00
|
|
|
Router, ServiceExt, extract::Request, handler::Handler, response::IntoResponse,
|
|
|
|
routing::Route,
|
2024-08-19 16:43:31 +02:00
|
|
|
},
|
|
|
|
std::{
|
|
|
|
convert::Infallible,
|
|
|
|
io,
|
|
|
|
net::{IpAddr, Ipv4Addr, SocketAddr},
|
|
|
|
},
|
2024-06-30 23:39:00 +02:00
|
|
|
tokio::net::TcpListener,
|
2025-03-07 18:21:23 +01:00
|
|
|
tower::{Service, layer::Layer},
|
2024-06-26 10:20:52 +02:00
|
|
|
tower_http::{
|
|
|
|
cors::CorsLayer,
|
|
|
|
normalize_path::NormalizePathLayer,
|
|
|
|
trace,
|
|
|
|
trace::{HttpMakeClassifier, TraceLayer},
|
|
|
|
},
|
2025-03-07 18:21:23 +01:00
|
|
|
tracing::{Level, info},
|
2024-06-26 10:20:52 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
// TODO trim trailing slash into macro > let _app = NormalizePathLayer::trim_trailing_slash().layer(create_app!(routes));
|
2024-06-22 17:19:55 +02:00
|
|
|
#[macro_export]
|
|
|
|
macro_rules! create_app {
|
|
|
|
($router:expr) => {
|
|
|
|
$router
|
|
|
|
};
|
|
|
|
($router:expr, $($layer:expr),* $(,)?) => {
|
|
|
|
$router$(.layer($layer))*
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-06-26 10:20:52 +02:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct AppBuilder {
|
|
|
|
router: Router,
|
2024-07-07 15:13:13 +02:00
|
|
|
socket: Option<(IpAddr, u16)>,
|
2024-06-26 10:20:52 +02:00
|
|
|
cors: Option<CorsLayer>,
|
|
|
|
normalize_path: Option<bool>,
|
|
|
|
tracing: Option<TraceLayer<HttpMakeClassifier>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AppBuilder {
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Creates a new app builder with default options.
|
2024-06-26 10:20:52 +02:00
|
|
|
pub fn new() -> Self {
|
|
|
|
Self::default()
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Creates the builder from the given router.
|
|
|
|
/// Only the routes and layers will be used.
|
2024-08-26 17:14:39 +02:00
|
|
|
pub fn from_router(router: Router) -> Self {
|
|
|
|
Self {
|
|
|
|
router,
|
|
|
|
..Self::default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Adds a route to the previously added routes
|
2024-06-28 19:16:40 +02:00
|
|
|
pub fn route(mut self, route: Router) -> Self {
|
|
|
|
self.router = self.router.merge(route);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Adds multiple routes to the previously added routes
|
2024-06-27 00:12:47 +02:00
|
|
|
pub fn routes(mut self, routes: impl IntoIterator<Item = Router>) -> Self {
|
|
|
|
self.router = routes.into_iter().fold(self.router, Router::merge);
|
2024-06-26 10:20:52 +02:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-19 16:43:31 +02:00
|
|
|
/// Adds a layer to the previously added routes
|
|
|
|
pub fn layer<L>(mut self, layer: L) -> Self
|
|
|
|
where
|
2025-03-07 18:21:23 +01:00
|
|
|
L: Layer<Route> + Clone + Send + Sync + 'static,
|
|
|
|
L::Service: Service<Request> + Clone + Send + Sync + 'static,
|
2024-08-19 16:43:31 +02:00
|
|
|
<L::Service as Service<Request>>::Response: IntoResponse + 'static,
|
|
|
|
<L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
|
|
|
|
<L::Service as Service<Request>>::Future: Send + 'static,
|
|
|
|
{
|
|
|
|
self.router = self.router.layer(layer);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Sets the socket for the server.
|
2024-07-07 15:13:13 +02:00
|
|
|
pub fn socket<IP: Into<IpAddr>>(mut self, socket: impl Into<(IP, u16)>) -> Self {
|
|
|
|
let (ip, port) = socket.into();
|
|
|
|
self.socket = Some((ip.into(), port));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Sets the port for the server.
|
2024-07-07 15:13:13 +02:00
|
|
|
pub fn port(mut self, port: u16) -> Self {
|
|
|
|
self.socket = if let Some((ip, _)) = self.socket {
|
|
|
|
Some((ip, port))
|
|
|
|
} else {
|
|
|
|
Some((Ipv4Addr::UNSPECIFIED.into(), port))
|
|
|
|
};
|
2024-06-26 10:20:52 +02:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Sets the fallback handler.
|
2024-06-26 10:20:52 +02:00
|
|
|
pub fn fallback<H, T>(mut self, fallback: H) -> Self
|
|
|
|
where
|
|
|
|
H: Handler<T, ()>,
|
|
|
|
T: 'static,
|
|
|
|
{
|
|
|
|
self.router = self.router.fallback(fallback);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Sets the cors layer.
|
2024-06-26 10:20:52 +02:00
|
|
|
pub fn cors(mut self, cors: CorsLayer) -> Self {
|
|
|
|
self.cors = Some(cors);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Sets the normalize path option. Default is true.
|
2024-06-26 10:20:52 +02:00
|
|
|
pub fn normalize_path(mut self, normalize_path: bool) -> Self {
|
|
|
|
self.normalize_path = Some(normalize_path);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-27 00:21:25 +02:00
|
|
|
/// Sets the trace layer.
|
2024-06-26 10:20:52 +02:00
|
|
|
pub fn tracing(mut self, tracing: TraceLayer<HttpMakeClassifier>) -> Self {
|
|
|
|
self.tracing = Some(tracing);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2024-08-26 17:14:39 +02:00
|
|
|
/// Creates the app with the given options.
|
|
|
|
/// This method is useful for testing purposes.
|
|
|
|
/// Options used for configuring the listener will be lost.
|
|
|
|
pub fn build(self) -> Router {
|
|
|
|
let mut app = self.router;
|
|
|
|
if let Some(cors) = self.cors {
|
|
|
|
app = app.layer(cors);
|
|
|
|
}
|
|
|
|
app.layer(
|
|
|
|
self.tracing.unwrap_or(
|
|
|
|
TraceLayer::new_for_http()
|
|
|
|
.make_span_with(trace::DefaultMakeSpan::new().level(Level::INFO))
|
|
|
|
.on_response(trace::DefaultOnResponse::new().level(Level::INFO)),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-08-19 16:43:31 +02:00
|
|
|
/// Build the app and start the server
|
|
|
|
/// # Default Options
|
|
|
|
/// - IP == 0.0.0.0
|
|
|
|
/// - Port == 8000
|
|
|
|
/// - Cors == None
|
|
|
|
/// - Normalize Path == true
|
|
|
|
/// - Tracing == Default compact
|
2024-06-26 10:20:52 +02:00
|
|
|
pub async fn serve(self) -> io::Result<()> {
|
2024-06-30 20:16:17 +02:00
|
|
|
let _ = fmt_trace(); // Allowed to fail
|
2024-06-26 10:31:20 +02:00
|
|
|
let listener = self.listener().await?;
|
2024-06-26 10:20:52 +02:00
|
|
|
|
2024-09-08 17:27:20 +02:00
|
|
|
let should_normalize = self.normalize_path.unwrap_or(true);
|
|
|
|
let app = self.build();
|
|
|
|
|
|
|
|
if should_normalize {
|
|
|
|
let app = NormalizePathLayer::trim_trailing_slash().layer(app);
|
2024-06-26 10:20:52 +02:00
|
|
|
axum::serve(listener, ServiceExt::<Request>::into_make_service(app)).await?;
|
|
|
|
} else {
|
|
|
|
axum::serve(listener, app.into_make_service()).await?;
|
|
|
|
};
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn listener(&self) -> io::Result<TcpListener> {
|
2024-07-07 15:13:13 +02:00
|
|
|
let addr = SocketAddr::from(self.socket.unwrap_or((Ipv4Addr::UNSPECIFIED.into(), 8000)));
|
2024-06-26 10:20:52 +02:00
|
|
|
info!("Initializing server on: {addr}");
|
|
|
|
TcpListener::bind(&addr).await
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn fmt_trace() -> Result<(), String> {
|
|
|
|
tracing_subscriber::fmt()
|
|
|
|
.with_target(false)
|
|
|
|
.compact()
|
|
|
|
.try_init()
|
|
|
|
.map_err(|error| error.to_string())
|
|
|
|
}
|
|
|
|
|
2024-06-30 20:16:17 +02:00
|
|
|
#[cfg(test)]
|
2024-06-22 17:19:55 +02:00
|
|
|
mod tests {
|
2024-06-26 10:20:52 +02:00
|
|
|
use super::*;
|
2024-08-27 00:21:25 +02:00
|
|
|
use axum::Router;
|
|
|
|
use std::time::Duration;
|
|
|
|
use tokio::time::sleep;
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_app_builder_serve() {
|
|
|
|
let handler = tokio::spawn(async {
|
|
|
|
AppBuilder::new().serve().await.unwrap();
|
|
|
|
});
|
|
|
|
sleep(Duration::from_millis(250)).await;
|
|
|
|
handler.abort();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_app_builder_all() {
|
|
|
|
let handler = tokio::spawn(async {
|
|
|
|
AppBuilder::new()
|
|
|
|
.socket((Ipv4Addr::LOCALHOST, 8080))
|
|
|
|
.routes([Router::new()])
|
|
|
|
.fallback(|| async { "Fallback" })
|
|
|
|
.cors(CorsLayer::new())
|
|
|
|
.normalize_path(true)
|
|
|
|
.tracing(TraceLayer::new_for_http())
|
|
|
|
.layer(TraceLayer::new_for_http())
|
|
|
|
.serve()
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
});
|
|
|
|
sleep(Duration::from_millis(250)).await;
|
|
|
|
handler.abort();
|
2024-06-26 10:20:52 +02:00
|
|
|
}
|
|
|
|
|
2024-06-22 17:19:55 +02:00
|
|
|
#[test]
|
|
|
|
fn test_create_app_router_only() {
|
|
|
|
let _app: Router<()> = create_app!(Router::new());
|
|
|
|
}
|
|
|
|
}
|