1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! Middleware tools
use crate::{
App, HttpResult,
http::{FromRequestRef, IntoResponse, MapErr, request::IntoTapResult},
not_found,
routing::{Route, RouteGroup},
};
use futures_util::future::BoxFuture;
use make_fn::*;
use std::sync::Arc;
#[cfg(feature = "di")]
use crate::di::FromContainer;
pub use handler::{Filter, MapOk, Middleware, Next, TapReq, With};
pub use http_context::HttpContext;
pub(crate) use make_fn::from_handler;
#[cfg(any(
feature = "compression-brotli",
feature = "compression-gzip",
feature = "compression-zstd",
feature = "compression-full"
))]
pub mod compress;
pub mod cors;
#[cfg(any(
feature = "decompression-brotli",
feature = "decompression-gzip",
feature = "decompression-zstd",
feature = "decompression-full"
))]
pub mod decompress;
pub mod handler;
pub mod http_context;
pub(super) mod make_fn;
const DEFAULT_MW_CAPACITY: usize = 8;
/// Points to the next middleware or request handler
pub type NextFn = Arc<dyn Fn(HttpContext) -> BoxFuture<'static, HttpResult> + Send + Sync>;
/// Point to a middleware function
pub(super) type MiddlewareFn =
Arc<dyn Fn(HttpContext, NextFn) -> BoxFuture<'static, HttpResult> + Send + Sync>;
/// Middleware pipeline
#[derive(Clone)]
pub(super) struct Middlewares {
pub(super) pipeline: Vec<MiddlewareFn>,
}
impl From<MiddlewareFn> for Middlewares {
#[inline]
fn from(mw: MiddlewareFn) -> Self {
let mut middlewares = Self::new();
middlewares.add(mw);
middlewares
}
}
impl Middlewares {
/// Initializes a new middleware pipeline
pub(super) fn new() -> Self {
Self {
pipeline: Vec::with_capacity(DEFAULT_MW_CAPACITY),
}
}
/// Returns `true` if there are no middlewares,
/// otherwise `false`
pub(super) fn is_empty(&self) -> bool {
self.pipeline.is_empty()
}
/// Adds middleware function to the pipeline
#[inline]
pub(super) fn add(&mut self, middleware: MiddlewareFn) {
self.pipeline.push(middleware);
}
/// Composes middlewares into a "Linked List" and returns head
pub(super) fn compose(&self) -> Option<NextFn> {
let mut iter = self.pipeline.iter().rev();
// Fetching the last middleware which is the request handler to be the initial `next`
let last = iter.next()?;
let mut next: NextFn = {
let handler = last.clone();
// Allocate the placeholder once at compose time, not per-request
let dummy: NextFn = Arc::new(|_| Box::pin(async { not_found!() }));
Arc::new(move |ctx| handler(ctx, dummy.clone()))
};
for mw in iter {
let current_mw = mw.clone();
let prev_next = next.clone();
next = Arc::new(move |ctx| current_mw(ctx, prev_next.clone()));
}
Some(next)
}
}
/// Middleware specific impl
impl App {
/// Wraps the application request pipeline with an inline middleware closure.
///
/// `wrap` is ideal for simple inline middleware.
/// For reusable or parameterized middleware types, use [`attach`](Self::attach).
///
/// # Examples
/// ```no_run
/// use volga::App;
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.wrap(|ctx, next| async move {
/// next(ctx).await
/// });
///# app.run().await
///# }
/// ```
///
/// # Timeouts
///
/// The pipeline does not enforce per-request timeouts. If your middleware
/// performs a long-running or potentially unbounded operation, check the
/// [`CancellationToken`](crate::CancellationToken) injected into each
/// request's extensions to avoid holding connections open indefinitely:
///
/// ```no_run
/// use volga::{App, CancellationToken, error::Error};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.wrap(|ctx, next| async move {
/// let token = ctx.extract::<CancellationToken>()?;
/// tokio::select! {
/// res = next(ctx) => res,
/// _ = token.cancelled() => Err(Error::server_error("request cancelled")),
/// }
/// });
///# app.run().await
///# }
/// ```
pub fn wrap<F, Fut>(&mut self, middleware: F) -> &mut Self
where
F: Fn(HttpContext, NextFn) -> Fut + Send + Sync + 'static,
Fut: Future<Output = HttpResult> + Send + 'static,
{
self.pipeline.middlewares_mut().add(make_fn(middleware));
self
}
/// Attaches a middleware to the application request pipeline.
///
/// Unlike [`wrap`](Self::wrap), which is optimized for inline closures,
/// `attach` is intended for reusable and parameterized middleware types.
///
/// This allows defining middleware as structs with configuration and state,
/// similar to middleware patterns found in other ecosystems.
///
/// # Parameterized middleware
/// ```no_run
/// use std::time::Duration;
/// use volga::{App, HttpResult, middleware::{HttpContext, NextFn, Middleware}};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.attach(Timeout {
/// duration: Duration::from_secs(1),
/// });
///# app.run().await
///# }
///
/// struct Timeout {
/// duration: Duration,
/// }
///
/// impl Middleware for Timeout {
/// fn call(&self, ctx: HttpContext, next: NextFn) -> impl Future<Output = HttpResult> + 'static {
/// let duration = self.duration;
/// async move {
/// tokio::time::sleep(duration).await;
/// next(ctx).await
/// }
/// }
/// }
/// ```
///
/// # Closure middleware
/// `attach` also accepts closures, but type annotations are required:
///
/// ```no_run
/// use volga::{App, middleware::{HttpContext, NextFn}};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.attach(|ctx: HttpContext, next: NextFn| async move {
/// next(ctx).await
/// });
///# app.run().await
///# }
/// ```
///
/// For simpler inline middleware without type annotations,
/// prefer [`wrap`](Self::wrap).
pub fn attach<F>(&mut self, middleware: F) -> &mut Self
where
F: Middleware,
{
self.pipeline.middlewares_mut().add(make_fn(middleware));
self
}
/// Adds a filter middleware handler for a request pipeline that would return
/// either `bool`, [`Result`] or [`FilterResult`]
/// and breaks the middleware chain if it's a `false` or [`Err`] values
///
/// > **Note:** [`Path`] and [`NamedPath`] extractors are not meaningful in a global
/// > filter context since they depend on route-specific parameters. Use
/// > them only when registering a filter for a specific route.
/// > Attempting to extract route parameters globally will result in an
/// > extraction error for routes that don't define those parameters.
///
/// # Example
/// ```no_run
/// use volga::{App, headers::HttpHeaders};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.filter(|headers: HttpHeaders| async move {
/// headers.get_raw("x-api-key").is_some()
/// });
///
/// app.map_get("/sum", |x: i32, y: i32| async move { x + y });
///# app.run().await
///# }
/// ```
pub fn filter<F, Args>(&mut self, filter: F) -> &mut Self
where
F: Filter<Args>,
Args: FromRequestRef + Send + 'static,
{
self.pipeline.middlewares_mut().add(make_filter_fn(filter));
self
}
/// Adds a middleware called when [`HttpResult`] is [`Ok`]
///
/// # Example
/// ```no_run
/// use volga::{App, HttpResponse, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "x-custom-header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.map_ok(|mut resp: HttpResponse| async move {
/// resp.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// resp
/// });
///
/// app.map_get("/sum", |x: i32, y: i32| async move { x + y });
///
///# app.run().await
///# }
/// ```
pub fn map_ok<F, R, Args>(&mut self, map: F) -> &mut Self
where
F: MapOk<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
self.pipeline.middlewares_mut().add(make_map_ok_fn(map));
self
}
/// Registers request-tapping middleware.
///
/// The middleware receives ownership of the incoming request and may
/// transform it before it is passed to the next stage.
///
/// The return type may be either:
/// - `HttpRequestMut`
/// - `Result<HttpRequestMut, Error>`
///
/// See [`IntoTapResult`] for details.
///
/// # Example
/// ```no_run
/// use volga::{App, HttpRequestMut, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "X-Custom-Header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.tap_req(|mut req: HttpRequestMut| async move {
/// req.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// req
/// });
///
/// app.map_get("/sum", |x: i32, y: i32| async move { x + y });
///
///# app.run().await
///# }
/// ```
///
/// # Security
///
/// `tap_req` grants full mutable ownership of the incoming request, including
/// all headers. Security-critical values such as `Authorization` can be
/// stripped or overwritten before downstream middleware and handlers observe
/// them. Only register trusted closures and be mindful that registration order
/// determines which code sees the original request.
#[cfg(feature = "di")]
pub fn tap_req<F, Args, R>(&mut self, map: F) -> &mut Self
where
F: TapReq<Args, Output = R>,
R: IntoTapResult,
Args: FromContainer + Send + 'static,
{
self.pipeline.middlewares_mut().add(make_tap_req_fn(map));
self
}
/// Registers request-tapping middleware.
///
/// The middleware receives ownership of the incoming request and may
/// transform it before it is passed to the next stage.
///
/// The return type may be either:
/// - `HttpRequestMut`
/// - `Result<HttpRequestMut, Error>`
///
/// See [`IntoTapResult`] for details.
///
/// # Example
/// ```no_run
/// use volga::{App, HttpRequestMut, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "X-Custom-Header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.tap_req(|mut req: HttpRequestMut| async move {
/// req.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// req
/// });
///
/// app.map_get("/sum", |x: i32, y: i32| async move { x + y });
///
///# app.run().await
///# }
/// ```
///
/// # Security
///
/// `tap_req` grants full mutable ownership of the incoming request, including
/// all headers. Security-critical values such as `Authorization` can be
/// stripped or overwritten before downstream middleware and handlers observe
/// them. Only register trusted closures and be mindful that registration order
/// determines which code sees the original request.
#[cfg(not(feature = "di"))]
pub fn tap_req<F, R>(&mut self, map: F) -> &mut Self
where
F: TapReq<Output = R>,
R: IntoTapResult,
{
self.pipeline.middlewares_mut().add(make_tap_req_fn(map));
self
}
/// Adds a middleware that can take any parameters that implement [`FromRequestRef`]
/// and the reference to the [`Next`] future; awaiting this `next` calls
/// the next middleware in the pipeline
///
/// Unlike the [`wrap`], this method doesn't provide direct access to the [`HttpRequest`] and [`HttpBody`]
///
/// # Example
/// ```no_run
/// use volga::{App, headers::HttpHeaders};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.with(|headers: HttpHeaders, next| async move {
/// // do something with headers
/// // ...
/// next.await
/// });
///# app.run().await
///# }
/// ```
pub fn with<F, R, Args>(&mut self, middleware: F) -> &mut Self
where
F: With<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
self.pipeline
.middlewares_mut()
.add(make_with_fn(middleware));
self
}
/// Registers default middleware
pub(super) fn use_endpoints(&mut self) {
if self.pipeline.has_middleware_pipeline() {
self.wrap(|ctx: HttpContext, _: NextFn| async move { ctx.execute().await });
}
}
}
impl<'a> Route<'a> {
/// Adds a middleware handler to this route request pipeline
///
/// # Examples
/// ```no_run
/// use volga::App;
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/hello", || async { "Hello, World!" })
/// .wrap(|ctx, next| async move {
/// next(ctx).await
/// });
///
///# app.run().await
///# }
/// ```
pub fn wrap<F, Fut>(self, middleware: F) -> Self
where
F: Fn(HttpContext, NextFn) -> Fut + Send + Sync + 'static,
Fut: Future<Output = HttpResult> + Send + 'static,
{
self.map_middleware(make_fn(middleware))
}
/// Attaches a middleware to this route request pipeline.
///
/// Unlike [`wrap`](Self::wrap), which is optimized for inline closures,
/// `attach` is intended for reusable and parameterized middleware types.
///
/// This allows defining middleware as structs with configuration and state,
/// similar to middleware patterns found in other ecosystems.
///
/// # Parameterized middleware
/// ```no_run
/// use std::time::Duration;
/// use volga::{App, HttpResult, middleware::{HttpContext, NextFn, Middleware}};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/hello", || async { "Hello, World!" })
/// .attach(Timeout {
/// duration: Duration::from_secs(1),
/// });
///# app.run().await
///# }
///
/// struct Timeout {
/// duration: Duration,
/// }
///
/// impl Middleware for Timeout {
/// fn call(&self, ctx: HttpContext, next: NextFn) -> impl Future<Output = HttpResult> + 'static {
/// let duration = self.duration;
/// async move {
/// tokio::time::sleep(duration).await;
/// next(ctx).await
/// }
/// }
/// }
/// ```
///
/// # Closure middleware
/// `attach` also accepts closures, but type annotations are required:
///
/// ```no_run
/// use volga::{App, middleware::{HttpContext, NextFn}};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/hello", || async { "Hello, World!" })
/// .attach(|ctx: HttpContext, next: NextFn| async move {
/// next(ctx).await
/// });
///# app.run().await
///# }
/// ```
///
/// For simpler inline middleware without type annotations,
/// prefer [`wrap`](Self::wrap).
pub fn attach<F>(self, middleware: F) -> Self
where
F: Middleware,
{
self.map_middleware(make_fn(middleware))
}
/// Adds a filter middleware handler for this route that would return
/// either `bool`, [`Result`] or [`FilterResult`]
/// and breaks the middleware chain if it's a `false` or [`Err`] values
///
/// # Example
/// ```no_run
/// use volga::{App, Path};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/sum", |x: i32, y: i32| async move { x + y })
/// .filter(|Path((x, y)): Path<(i32, i32)>| async move { x > 0 && y > 0 });
///
///# app.run().await
///# }
/// ```
pub fn filter<F, Args>(self, filter: F) -> Self
where
F: Filter<Args>,
Args: FromRequestRef + Send + 'static,
{
let filter_fn = make_filter_fn(filter);
self.map_middleware(filter_fn)
}
/// Adds middleware called for this route when [`HttpResult`] is [`Ok`]
///
/// # Example
/// ```no_run
/// use volga::{App, HttpResponse, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "x-custom-header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/sum", |x: i32, y: i32| async move { x + y })
/// .map_ok(|mut resp: HttpResponse| async move {
/// resp.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// resp
/// });
///
///# app.run().await
///# }
/// ```
pub fn map_ok<F, R, Args>(self, map: F) -> Self
where
F: MapOk<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
let map_ok_fn = make_map_ok_fn(map);
self.map_middleware(map_ok_fn)
}
/// Adds a middleware that called for this route when [`HttpResult`] is [`Err`]
///
/// # Example
/// ```no_run
/// use volga::{App, error::Error};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/sum", |x: i32, y: i32| async move { x + y })
/// .map_err(|err: Error| async move {
/// println!("{err:?}");
/// err
/// });
///
///# app.run().await
///# }
/// ```
pub fn map_err<F, R, Args>(self, map: F) -> Self
where
F: MapErr<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
let map_err_fn = make_map_err_fn(map);
self.map_middleware(map_err_fn)
}
/// Registers request-tapping middleware.
///
/// The middleware receives ownership of the incoming request and may
/// transform it before it is passed to the next stage.
///
/// The return type may be either:
/// - `HttpRequestMut`
/// - `Result<HttpRequestMut, Error>`
///
/// See [`IntoTapResult`] for details.
///
/// # Example
/// ```no_run
/// use volga::{App, HttpRequestMut, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "X-Custom-Header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/sum", |x: i32, y: i32| async move { x + y })
/// .tap_req(|mut req: HttpRequestMut| async move {
/// req.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// req
/// });
///
///# app.run().await
///# }
/// ```
///
/// # Security
///
/// `tap_req` grants full mutable ownership of the incoming request, including
/// all headers. Security-critical values such as `Authorization` can be
/// stripped or overwritten before downstream middleware and handlers observe
/// them. Only register trusted closures and be mindful that registration order
/// determines which code sees the original request.
#[cfg(feature = "di")]
pub fn tap_req<F, Args, R>(self, map: F) -> Self
where
F: TapReq<Args, Output = R>,
R: IntoTapResult,
Args: FromContainer + Send + 'static,
{
let map_err_fn = make_tap_req_fn(map);
self.map_middleware(map_err_fn)
}
/// Registers request-tapping middleware.
///
/// The middleware receives ownership of the incoming request and may
/// transform it before it is passed to the next stage.
///
/// The return type may be either:
/// - `HttpRequestMut`
/// - `Result<HttpRequestMut, Error>`
///
/// See [`IntoTapResult`] for details.
///
/// # Example
/// ```no_run
/// use volga::{App, HttpRequestMut, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "X-Custom-Header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app
/// .map_get("/sum", |x: i32, y: i32| async move { x + y })
/// .tap_req(|mut req: HttpRequestMut| async move {
/// req.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// req
/// });
///
///# app.run().await
///# }
/// ```
///
/// # Security
///
/// `tap_req` grants full mutable ownership of the incoming request, including
/// all headers. Security-critical values such as `Authorization` can be
/// stripped or overwritten before downstream middleware and handlers observe
/// them. Only register trusted closures and be mindful that registration order
/// determines which code sees the original request.
#[cfg(not(feature = "di"))]
pub fn tap_req<F, R>(self, map: F) -> Self
where
F: TapReq<Output = R>,
R: IntoTapResult,
{
let map_err_fn = make_tap_req_fn(map);
self.map_middleware(map_err_fn)
}
/// Adds a middleware for this route that can take any parameters that implement [`FromRequestRef`]
/// and the reference to the [`Next`] future; awaiting this `next` calls
/// the next middleware in the pipeline
///
/// Unlike the [`wrap`], this method doesn't provide direct access to the [`HttpRequest`] and [`HttpBody`]
///
/// # Example
/// ```no_run
/// use volga::{App, headers::HttpHeaders};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.with(|headers: HttpHeaders, next| async move {
/// // do something with headers
/// // ...
/// next.await
/// });
///# app.run().await
///# }
/// ```
pub fn with<F, R, Args>(self, middleware: F) -> Self
where
F: With<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
let with_fn = make_with_fn(middleware);
self.map_middleware(with_fn)
}
#[inline]
pub(crate) fn map_middleware(self, mw: MiddlewareFn) -> Self {
self.app.pipeline.endpoints_mut().map_layer(
self.method.clone(),
self.pattern.as_ref(),
mw.into(),
);
self
}
}
impl<'a> RouteGroup<'a> {
/// Adds a middleware handler to this group of routes
///
/// # Examples
/// ```no_run
/// use volga::App;
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/hello", |api| {
/// api.wrap(|ctx, next| async move { next(ctx).await });
/// api.map_get("/world", || async { "Hello, World!" });
/// });
///# app.run().await
///# }
/// ```
pub fn wrap<F, Fut>(&mut self, middleware: F) -> &mut Self
where
F: Fn(HttpContext, NextFn) -> Fut + Send + Sync + 'static,
Fut: Future<Output = HttpResult> + Send + 'static,
{
self.middleware.push(make_fn(middleware));
self
}
/// Attaches a middleware to this route group request pipeline.
///
/// Unlike [`wrap`](Self::wrap), which is optimized for inline closures,
/// `attach` is intended for reusable and parameterized middleware types.
///
/// This allows defining middleware as structs with configuration and state,
/// similar to middleware patterns found in other ecosystems.
///
/// # Parameterized middleware
/// ```no_run
/// use std::time::Duration;
/// use volga::{App, HttpResult, middleware::{HttpContext, NextFn, Middleware}};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/hello", |api| {
/// api.attach(Timeout {
/// duration: Duration::from_secs(1),
/// });
/// api.map_get("/world", || async { "Hello, World!" });
/// });
///# app.run().await
///# }
///
/// struct Timeout {
/// duration: Duration,
/// }
///
/// impl Middleware for Timeout {
/// fn call(&self, ctx: HttpContext, next: NextFn) -> impl Future<Output = HttpResult> + 'static {
/// let duration = self.duration;
/// async move {
/// tokio::time::sleep(duration).await;
/// next(ctx).await
/// }
/// }
/// }
/// ```
///
/// # Closure middleware
/// `attach` also accepts closures, but type annotations are required:
///
/// ```no_run
/// use volga::{App, middleware::{HttpContext, NextFn}};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/hello", |api| {
/// api.attach(|ctx: HttpContext, next: NextFn| async move {
/// next(ctx).await
/// });
/// api.map_get("/world", || async { "Hello, World!" });
/// });
///# app.run().await
///# }
/// ```
///
/// For simpler inline middleware without type annotations,
/// prefer [`wrap`](Self::wrap).
pub fn attach<F>(&mut self, middleware: F) -> &mut Self
where
F: Middleware,
{
self.middleware.push(make_fn(middleware));
self
}
/// Adds a filter middleware handler for a group of routes that would return
/// either `bool`, [`Result`] or [`FilterResult`]
/// and breaks the middleware chain if it's a `false` or [`Err`] values
///
/// > **Note:** [`Path`] and [`NamedPath`] extractors are not meaningful in a
/// > route group filter context since they depend on route-specific parameters. Use
/// > them only when registering a filter for a specific route.
/// > Attempting to extract route parameters globally will result in an
/// > extraction error for routes that don't define those parameters.
///
/// # Example
/// ```no_run
/// use volga::{App, headers::HttpHeaders};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/positive", |api| {
/// api.filter(|headers: HttpHeaders| async move {
/// headers.get_raw("x-api-key").is_some()
/// });
///
/// api.map_get("/sum", |x: i32, y: i32| async move { x + y });
/// api.map_get("/mul", |x: i32, y: i32| async move { x * y });
/// });
///# app.run().await
///# }
/// ```
pub fn filter<F, Args>(&mut self, filter: F) -> &mut Self
where
F: Filter<Args>,
Args: FromRequestRef + Send + 'static,
{
let filter_fn = make_filter_fn(filter);
self.middleware.push(filter_fn);
self
}
/// Adds middleware called for this group of routes when [`HttpResult`] is [`Ok`]
///
/// # Example
/// ```no_run
/// use volga::{App, HttpResponse, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "x-custom-header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/positive", |api| {
/// api.map_ok(|mut resp: HttpResponse| async move {
/// resp.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// resp
/// });
/// api.map_get("/sum", |x: i32, y: i32| async move {
/// x + y
/// });
/// });
///# app.run().await
///# }
/// ```
pub fn map_ok<F, R, Args>(&mut self, map: F) -> &mut Self
where
F: MapOk<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
let map_ok_fn = make_map_ok_fn(map);
self.middleware.push(map_ok_fn);
self
}
/// Adds a middleware that called for this group of routes when [`HttpResult`] is [`Err`]
///
/// # Example
/// ```no_run
/// use volga::{App, error::Error};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/positive", |api| {
/// api.map_err(|err: Error| async move {
/// println!("{err:?}");
/// err
/// });
/// api.map_get("/sum", |x: i32, y: i32| async move {
/// x + y
/// });
/// });
///# app.run().await
///# }
/// ```
pub fn map_err<F, R, Args>(&mut self, map: F) -> &mut Self
where
F: MapErr<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
let map_err_fn = make_map_err_fn(map);
self.middleware.push(map_err_fn);
self
}
/// Registers request-tapping middleware.
///
/// The middleware receives ownership of the incoming request and may
/// transform it before it is passed to the next stage.
///
/// The return type may be either:
/// - `HttpRequestMut`
/// - `Result<HttpRequestMut, Error>`
///
/// See [`IntoTapResult`] for details.
///
/// # Example
/// ```no_run
/// use volga::{App, HttpRequestMut, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "X-Custom-Header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/positive", |api| {
/// api.tap_req(|mut req: HttpRequestMut| async move {
/// req.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// req
/// });
/// api.map_get("/sum", |x: i32, y: i32| async move {
/// x + y
/// });
/// });
///# app.run().await
///# }
/// ```
///
/// # Security
///
/// `tap_req` grants full mutable ownership of the incoming request, including
/// all headers. Security-critical values such as `Authorization` can be
/// stripped or overwritten before downstream middleware and handlers observe
/// them. Only register trusted closures and be mindful that registration order
/// determines which code sees the original request.
#[cfg(feature = "di")]
pub fn tap_req<F, Args, R>(&mut self, map: F) -> &mut Self
where
F: TapReq<Args, Output = R>,
R: IntoTapResult,
Args: FromContainer + Send + 'static,
{
let tap_req_fn = make_tap_req_fn(map);
self.middleware.push(tap_req_fn);
self
}
/// Registers request-tapping middleware.
///
/// The middleware receives ownership of the incoming request and may
/// transform it before it is passed to the next stage.
///
/// The return type may be either:
/// - `HttpRequestMut`
/// - `Result<HttpRequestMut, Error>`
///
/// See [`IntoTapResult`] for details.
///
/// # Example
/// ```no_run
/// use volga::{App, HttpRequestMut, headers::{Header, headers}};
///
/// headers! {
/// (CustomHeader, "X-Custom-Header")
/// }
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/positive", |api| {
/// api.tap_req(|mut req: HttpRequestMut| async move {
/// req.insert_header(Header::<CustomHeader>::from_static("Custom Value"));
/// req
/// });
/// api.map_get("/sum", |x: i32, y: i32| async move {
/// x + y
/// });
/// });
///# app.run().await
///# }
/// ```
///
/// # Security
///
/// `tap_req` grants full mutable ownership of the incoming request, including
/// all headers. Security-critical values such as `Authorization` can be
/// stripped or overwritten before downstream middleware and handlers observe
/// them. Only register trusted closures and be mindful that registration order
/// determines which code sees the original request.
#[cfg(not(feature = "di"))]
pub fn tap_req<F, R>(&mut self, map: F) -> &mut Self
where
F: TapReq<Output = R>,
R: IntoTapResult,
{
let tap_req_fn = make_tap_req_fn(map);
self.middleware.push(tap_req_fn);
self
}
/// Adds middleware for this group of routes that can take any parameters that implement [`FromRequestRef`]
/// and the reference to the [`Next`] future; awaiting this `next` calls
/// the next middleware in the pipeline
///
/// Unlike the [`wrap`], this method doesn't provide direct access to the [`HttpRequest`] and [`HttpBody`]
///
/// # Example
/// ```no_run
/// use volga::{App, headers::HttpHeaders};
///
///# #[tokio::main]
///# async fn main() -> std::io::Result<()> {
/// let mut app = App::new();
///
/// app.group("/hello", |api| {
/// api.with(|headers: HttpHeaders, next| async move {
/// // do something with headers
/// // ...
/// next.await
/// });
///
/// api.map_get("/world", || async { "Hello, World!" });
/// });
///# app.run().await
///# }
/// ```
pub fn with<F, R, Args>(&mut self, middleware: F) -> &mut Self
where
F: With<Args, Output = R>,
R: IntoResponse + 'static,
Args: FromRequestRef + Send + 'static,
{
let with_fn = make_with_fn(middleware);
self.middleware.push(with_fn);
self
}
}