@@ -6,22 +6,25 @@ use axum::{
66 response:: { IntoResponse , Response } ,
77} ;
88use std:: { future:: Future , sync:: Arc } ;
9+ use tower_http:: compression:: CompressionLayer ;
910
10- use crate :: handler:: AppState ;
11+ pub use crate :: handler:: AppState ;
12+
13+ pub type AppRouter = Router < AppState > ;
1114
1215/// Object-safe middleware trait for applying HTTP middleware to the server `Router`.
1316///
1417/// This is intentionally type-erased so callers can register arbitrary axum/tower
1518/// middleware without turning `ServerBuilder` into a giant generic type.
1619pub trait HttpMiddleware : Send + Sync + ' static {
17- fn apply ( & self , router : Router < AppState > ) -> Router < AppState > ;
20+ fn apply ( & self , router : AppRouter ) -> AppRouter ;
1821}
1922
2023impl < F > HttpMiddleware for F
2124where
22- F : Fn ( Router < AppState > ) -> Router < AppState > + Send + Sync + ' static ,
25+ F : Fn ( AppRouter ) -> AppRouter + Send + Sync + ' static ,
2326{
24- fn apply ( & self , router : Router < AppState > ) -> Router < AppState > {
27+ fn apply ( & self , router : AppRouter ) -> AppRouter {
2528 ( self ) ( router)
2629 }
2730}
@@ -42,11 +45,36 @@ where
4245 F : Fn ( Request , Next ) -> Fut + Clone + Send + Sync + ' static ,
4346 Fut : Future < Output = Response > + Send + ' static ,
4447{
45- fn apply ( & self , router : Router < AppState > ) -> Router < AppState > {
48+ fn apply ( & self , router : AppRouter ) -> AppRouter {
4649 router. layer ( axum:: middleware:: from_fn ( self . f . clone ( ) ) )
4750 }
4851}
4952
53+ /// Middleware that applies response compression using `tower-http`'s `CompressionLayer`.
54+ pub struct CompressionMiddleware {
55+ layer : CompressionLayer ,
56+ }
57+
58+ impl CompressionMiddleware {
59+ pub fn new ( layer : CompressionLayer ) -> Self {
60+ Self { layer }
61+ }
62+ }
63+
64+ impl Default for CompressionMiddleware {
65+ fn default ( ) -> Self {
66+ Self {
67+ layer : CompressionLayer :: new ( ) ,
68+ }
69+ }
70+ }
71+
72+ impl HttpMiddleware for CompressionMiddleware {
73+ fn apply ( & self , router : AppRouter ) -> AppRouter {
74+ router. layer ( self . layer . clone ( ) )
75+ }
76+ }
77+
5078/// A simple API key middleware that validates `x-api-key` on every request.
5179///
5280/// Use `exempt_path` to allow unauthenticated endpoints (e.g. health/info routes).
@@ -72,7 +100,7 @@ impl ApiKeyMiddleware {
72100}
73101
74102impl HttpMiddleware for ApiKeyMiddleware {
75- fn apply ( & self , router : Router < AppState > ) -> Router < AppState > {
103+ fn apply ( & self , router : AppRouter ) -> AppRouter {
76104 let expected_key = self . expected_key . clone ( ) ;
77105 let exempt_paths = self . exempt_paths . clone ( ) ;
78106
0 commit comments