-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathextract.rs
More file actions
2146 lines (1875 loc) · 64.6 KB
/
extract.rs
File metadata and controls
2146 lines (1875 loc) · 64.6 KB
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
//! Extractors for RustAPI
//!
//! Extractors automatically parse and validate data from incoming HTTP requests.
//! They implement the [`FromRequest`] or [`FromRequestParts`] traits and can be
//! used as handler function parameters.
//!
//! # Available Extractors
//!
//! | Extractor | Description | Consumes Body |
//! |-----------|-------------|---------------|
//! | [`Json<T>`] | Parse JSON request body | Yes |
//! | [`ValidatedJson<T>`] | Parse and validate JSON body | Yes |
//! | [`Query<T>`] | Parse query string parameters | No |
//! | [`Path<T>`] | Extract path parameters | No |
//! | [`State<T>`] | Access shared application state | No |
//! | [`Body`] | Raw request body bytes | Yes |
//! | [`Headers`] | Access all request headers | No |
//! | [`HeaderValue`] | Extract a specific header | No |
//! | [`Extension<T>`] | Access middleware-injected data | No |
//! | [`ClientIp`] | Extract client IP address | No |
//! | [`Cookies`] | Parse request cookies (requires `cookies` feature) | No |
//!
//! # Example
//!
//! ```rust,ignore
//! use rustapi_core::{Json, Query, Path, State};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Deserialize)]
//! struct CreateUser {
//! name: String,
//! email: String,
//! }
//!
//! #[derive(Deserialize)]
//! struct Pagination {
//! page: Option<u32>,
//! limit: Option<u32>,
//! }
//!
//! // Multiple extractors can be combined
//! async fn create_user(
//! State(db): State<DbPool>,
//! Query(pagination): Query<Pagination>,
//! Json(body): Json<CreateUser>,
//! ) -> impl IntoResponse {
//! // Use db, pagination, and body...
//! }
//! ```
//!
//! # Extractor Order
//!
//! When using multiple extractors, body-consuming extractors (like `Json` or `Body`)
//! must come last since they consume the request body. Non-body extractors can be
//! in any order.
use crate::error::{ApiError, Result};
use crate::json;
use crate::request::Request;
use crate::response::IntoResponse;
use crate::stream::{StreamingBody, StreamingConfig};
use crate::validation::Validatable;
use bytes::Bytes;
use http::{header, StatusCode};
use rustapi_validate::v2::{AsyncValidate, ValidationContext};
use rustapi_openapi::schema::{RustApiSchema, SchemaCtx, SchemaRef};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::BTreeMap;
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
/// Trait for extracting data from request parts (headers, path, query)
///
/// This is used for extractors that don't need the request body.
///
/// # Example: Implementing a custom extractor that requires a specific header
///
/// ```rust
/// use rustapi_core::FromRequestParts;
/// use rustapi_core::{Request, ApiError, Result};
/// use http::StatusCode;
///
/// struct ApiKey(String);
///
/// impl FromRequestParts for ApiKey {
/// fn from_request_parts(req: &Request) -> Result<Self> {
/// if let Some(key) = req.headers().get("x-api-key") {
/// if let Ok(key_str) = key.to_str() {
/// return Ok(ApiKey(key_str.to_string()));
/// }
/// }
/// Err(ApiError::unauthorized("Missing or invalid API key"))
/// }
/// }
/// ```
pub trait FromRequestParts: Sized {
/// Extract from request parts
fn from_request_parts(req: &Request) -> Result<Self>;
}
/// Trait for extracting data from the full request (including body)
///
/// This is used for extractors that consume the request body.
///
/// # Example: Implementing a custom extractor that consumes the body
///
/// ```rust
/// use rustapi_core::FromRequest;
/// use rustapi_core::{Request, ApiError, Result};
/// use std::future::Future;
///
/// struct PlainText(String);
///
/// impl FromRequest for PlainText {
/// async fn from_request(req: &mut Request) -> Result<Self> {
/// // Ensure body is loaded
/// req.load_body().await?;
///
/// // Consume the body
/// if let Some(bytes) = req.take_body() {
/// if let Ok(text) = String::from_utf8(bytes.to_vec()) {
/// return Ok(PlainText(text));
/// }
/// }
///
/// Err(ApiError::bad_request("Invalid plain text body"))
/// }
/// }
/// ```
pub trait FromRequest: Sized {
/// Extract from the full request
fn from_request(req: &mut Request) -> impl Future<Output = Result<Self>> + Send;
}
// Blanket impl: FromRequestParts -> FromRequest
impl<T: FromRequestParts> FromRequest for T {
async fn from_request(req: &mut Request) -> Result<Self> {
T::from_request_parts(req)
}
}
/// JSON body extractor
///
/// Parses the request body as JSON and deserializes into type `T`.
/// Also works as a response type when T: Serialize.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct CreateUser {
/// name: String,
/// email: String,
/// }
///
/// async fn create_user(Json(body): Json<CreateUser>) -> impl IntoResponse {
/// // body is already deserialized
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct Json<T>(pub T);
impl<T: DeserializeOwned + Send> FromRequest for Json<T> {
async fn from_request(req: &mut Request) -> Result<Self> {
req.load_body().await?;
let body = req
.take_body()
.ok_or_else(|| ApiError::internal("Body already consumed"))?;
// Use simd-json accelerated parsing when available (2-4x faster)
let value: T = json::from_slice(&body)?;
Ok(Json(value))
}
}
impl<T> Deref for Json<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Json<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for Json<T> {
fn from(value: T) -> Self {
Json(value)
}
}
/// Default pre-allocation size for JSON response buffers (256 bytes)
/// This covers most small to medium JSON responses without reallocation.
const JSON_RESPONSE_INITIAL_CAPACITY: usize = 256;
// IntoResponse for Json - allows using Json<T> as a return type
impl<T: Serialize> IntoResponse for Json<T> {
fn into_response(self) -> crate::response::Response {
// Use pre-allocated buffer to reduce allocations
match json::to_vec_with_capacity(&self.0, JSON_RESPONSE_INITIAL_CAPACITY) {
Ok(body) => http::Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json")
.body(crate::response::Body::from(body))
.unwrap(),
Err(err) => {
ApiError::internal(format!("Failed to serialize response: {}", err)).into_response()
}
}
}
}
/// Validated JSON body extractor
///
/// Parses the request body as JSON, deserializes into type `T`, and validates
/// using the `Validate` trait. Returns a 422 Unprocessable Entity error with
/// detailed field-level validation errors if validation fails.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
/// use validator::Validate;
///
/// #[derive(Deserialize, Validate)]
/// struct CreateUser {
/// #[validate(email)]
/// email: String,
/// #[validate(length(min = 8))]
/// password: String,
/// }
///
/// async fn register(ValidatedJson(body): ValidatedJson<CreateUser>) -> impl IntoResponse {
/// // body is already validated!
/// // If email is invalid or password too short, a 422 error is returned automatically
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidatedJson<T>(pub T);
impl<T> ValidatedJson<T> {
/// Create a new ValidatedJson wrapper
pub fn new(value: T) -> Self {
Self(value)
}
/// Get the inner value
pub fn into_inner(self) -> T {
self.0
}
}
impl<T: DeserializeOwned + Validatable + Send> FromRequest for ValidatedJson<T> {
async fn from_request(req: &mut Request) -> Result<Self> {
req.load_body().await?;
// First, deserialize the JSON body using simd-json when available
let body = req
.take_body()
.ok_or_else(|| ApiError::internal("Body already consumed"))?;
let value: T = json::from_slice(&body)?;
// Then, validate it using the unified Validatable trait
value.do_validate()?;
Ok(ValidatedJson(value))
}
}
impl<T> Deref for ValidatedJson<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for ValidatedJson<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for ValidatedJson<T> {
fn from(value: T) -> Self {
ValidatedJson(value)
}
}
impl<T: Serialize> IntoResponse for ValidatedJson<T> {
fn into_response(self) -> crate::response::Response {
Json(self.0).into_response()
}
}
/// Async validated JSON body extractor
///
/// Parses the request body as JSON, deserializes into type `T`, and validates
/// using the `AsyncValidate` trait from `rustapi-validate`.
///
/// This extractor supports async validation rules, such as database uniqueness checks.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
/// use rustapi_validate::v2::prelude::*;
///
/// #[derive(Deserialize, Validate, AsyncValidate)]
/// struct CreateUser {
/// #[validate(email)]
/// email: String,
///
/// #[validate(async_unique(table = "users", column = "email"))]
/// username: String,
/// }
///
/// async fn register(AsyncValidatedJson(body): AsyncValidatedJson<CreateUser>) -> impl IntoResponse {
/// // body is validated asynchronously (e.g. checked existing email in DB)
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct AsyncValidatedJson<T>(pub T);
impl<T> AsyncValidatedJson<T> {
/// Create a new AsyncValidatedJson wrapper
pub fn new(value: T) -> Self {
Self(value)
}
/// Get the inner value
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> Deref for AsyncValidatedJson<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for AsyncValidatedJson<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for AsyncValidatedJson<T> {
fn from(value: T) -> Self {
AsyncValidatedJson(value)
}
}
impl<T: Serialize> IntoResponse for AsyncValidatedJson<T> {
fn into_response(self) -> crate::response::Response {
Json(self.0).into_response()
}
}
impl<T: DeserializeOwned + AsyncValidate + Send + Sync> FromRequest for AsyncValidatedJson<T> {
async fn from_request(req: &mut Request) -> Result<Self> {
req.load_body().await?;
let body = req
.take_body()
.ok_or_else(|| ApiError::internal("Body already consumed"))?;
let value: T = json::from_slice(&body)?;
// Create validation context from request
// Check if validators are configured in App State
let ctx = if let Some(ctx) = req.state().get::<ValidationContext>() {
ctx.clone()
} else {
ValidationContext::default()
};
// Perform full validation (sync + async)
if let Err(errors) = value.validate_full(&ctx).await {
// Convert v2 ValidationErrors to ApiError
let field_errors: Vec<crate::error::FieldError> = errors
.fields
.iter()
.flat_map(|(field, errs)| {
let field_name = field.to_string();
errs.iter().map(move |e| crate::error::FieldError {
field: field_name.clone(),
code: e.code.to_string(),
message: e.message.clone(),
})
})
.collect();
return Err(ApiError::validation(field_errors));
}
Ok(AsyncValidatedJson(value))
}
}
/// Query string extractor
///
/// Parses the query string into type `T`.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct Pagination {
/// page: Option<u32>,
/// limit: Option<u32>,
/// }
///
/// async fn list_users(Query(params): Query<Pagination>) -> impl IntoResponse {
/// // params.page, params.limit
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Query<T>(pub T);
impl<T: DeserializeOwned> FromRequestParts for Query<T> {
fn from_request_parts(req: &Request) -> Result<Self> {
let query = req.query_string().unwrap_or("");
let value: T = serde_urlencoded::from_str(query)
.map_err(|e| ApiError::bad_request(format!("Invalid query string: {}", e)))?;
Ok(Query(value))
}
}
impl<T> Deref for Query<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Path parameter extractor
///
/// Extracts path parameters defined in the route pattern.
///
/// # Example
///
/// For route `/users/{id}`:
///
/// ```rust,ignore
/// async fn get_user(Path(id): Path<i64>) -> impl IntoResponse {
/// // id is extracted from path
/// }
/// ```
///
/// For multiple params `/users/{user_id}/posts/{post_id}`:
///
/// ```rust,ignore
/// async fn get_post(Path((user_id, post_id)): Path<(i64, i64)>) -> impl IntoResponse {
/// // Both params extracted
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Path<T>(pub T);
impl<T: FromStr> FromRequestParts for Path<T>
where
T::Err: std::fmt::Display,
{
fn from_request_parts(req: &Request) -> Result<Self> {
let params = req.path_params();
// For single param, get the first one
if let Some((_, value)) = params.iter().next() {
let parsed = value
.parse::<T>()
.map_err(|e| ApiError::bad_request(format!("Invalid path parameter: {}", e)))?;
return Ok(Path(parsed));
}
Err(ApiError::internal("Missing path parameter"))
}
}
impl<T> Deref for Path<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Typed path extractor
///
/// Extracts path parameters and deserializes them into a struct implementing `Deserialize`.
/// This is similar to `Path<T>`, but supports complex structs that can be deserialized
/// from a map of parameter names to values (e.g. via `serde_json`).
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct UserParams {
/// id: u64,
/// category: String,
/// }
///
/// async fn get_user(Typed(params): Typed<UserParams>) -> impl IntoResponse {
/// // params.id, params.category
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Typed<T>(pub T);
impl<T: DeserializeOwned + Send> FromRequestParts for Typed<T> {
fn from_request_parts(req: &Request) -> Result<Self> {
let params = req.path_params();
let mut map = serde_json::Map::new();
for (k, v) in params.iter() {
map.insert(k.to_string(), serde_json::Value::String(v.to_string()));
}
let value = serde_json::Value::Object(map);
let parsed: T = serde_json::from_value(value)
.map_err(|e| ApiError::bad_request(format!("Invalid path parameters: {}", e)))?;
Ok(Typed(parsed))
}
}
impl<T> Deref for Typed<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// State extractor
///
/// Extracts shared application state.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Clone)]
/// struct AppState {
/// db: DbPool,
/// }
///
/// async fn handler(State(state): State<AppState>) -> impl IntoResponse {
/// // Use state.db
/// }
/// ```
#[derive(Debug, Clone)]
pub struct State<T>(pub T);
impl<T: Clone + Send + Sync + 'static> FromRequestParts for State<T> {
fn from_request_parts(req: &Request) -> Result<Self> {
req.state().get::<T>().cloned().map(State).ok_or_else(|| {
ApiError::internal(format!(
"State of type `{}` not found. Did you forget to call .state()?",
std::any::type_name::<T>()
))
})
}
}
impl<T> Deref for State<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Raw body bytes extractor
#[derive(Debug, Clone)]
pub struct Body(pub Bytes);
impl FromRequest for Body {
async fn from_request(req: &mut Request) -> Result<Self> {
req.load_body().await?;
let body = req
.take_body()
.ok_or_else(|| ApiError::internal("Body already consumed"))?;
Ok(Body(body))
}
}
impl Deref for Body {
type Target = Bytes;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Streaming body extractor
pub struct BodyStream(pub StreamingBody);
impl FromRequest for BodyStream {
async fn from_request(req: &mut Request) -> Result<Self> {
let config = StreamingConfig::default();
if let Some(stream) = req.take_stream() {
Ok(BodyStream(StreamingBody::new(stream, config.max_body_size)))
} else if let Some(bytes) = req.take_body() {
// Handle buffered body as stream
let stream = futures_util::stream::once(async move { Ok(bytes) });
Ok(BodyStream(StreamingBody::from_stream(
stream,
config.max_body_size,
)))
} else {
Err(ApiError::internal("Body already consumed"))
}
}
}
impl Deref for BodyStream {
type Target = StreamingBody;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for BodyStream {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
// Forward stream implementation
impl futures_util::Stream for BodyStream {
type Item = Result<Bytes, ApiError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
std::pin::Pin::new(&mut self.0).poll_next(cx)
}
}
/// Optional extractor wrapper
///
/// Makes any extractor optional - returns None instead of error on failure.
impl<T: FromRequestParts> FromRequestParts for Option<T> {
fn from_request_parts(req: &Request) -> Result<Self> {
Ok(T::from_request_parts(req).ok())
}
}
/// Headers extractor
///
/// Provides access to all request headers as a typed map.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::Headers;
///
/// async fn handler(headers: Headers) -> impl IntoResponse {
/// if let Some(content_type) = headers.get("content-type") {
/// format!("Content-Type: {:?}", content_type)
/// } else {
/// "No Content-Type header".to_string()
/// }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Headers(pub http::HeaderMap);
impl Headers {
/// Get a header value by name
pub fn get(&self, name: &str) -> Option<&http::HeaderValue> {
self.0.get(name)
}
/// Check if a header exists
pub fn contains(&self, name: &str) -> bool {
self.0.contains_key(name)
}
/// Get the number of headers
pub fn len(&self) -> usize {
self.0.len()
}
/// Check if headers are empty
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Iterate over all headers
pub fn iter(&self) -> http::header::Iter<'_, http::HeaderValue> {
self.0.iter()
}
}
impl FromRequestParts for Headers {
fn from_request_parts(req: &Request) -> Result<Self> {
Ok(Headers(req.headers().clone()))
}
}
impl Deref for Headers {
type Target = http::HeaderMap;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Single header value extractor
///
/// Extracts a specific header value by name. Returns an error if the header is missing.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::HeaderValue;
///
/// async fn handler(
/// auth: HeaderValue<{ "authorization" }>,
/// ) -> impl IntoResponse {
/// format!("Auth header: {}", auth.0)
/// }
/// ```
///
/// Note: Due to Rust's const generics limitations, you may need to use the
/// `HeaderValueOf` type alias or extract headers manually using the `Headers` extractor.
#[derive(Debug, Clone)]
pub struct HeaderValue(pub String, pub &'static str);
impl HeaderValue {
/// Create a new HeaderValue extractor for a specific header name
pub fn new(name: &'static str, value: String) -> Self {
Self(value, name)
}
/// Get the header value
pub fn value(&self) -> &str {
&self.0
}
/// Get the header name
pub fn name(&self) -> &'static str {
self.1
}
/// Extract a specific header from a request
pub fn extract(req: &Request, name: &'static str) -> Result<Self> {
req.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(|s| HeaderValue(s.to_string(), name))
.ok_or_else(|| ApiError::bad_request(format!("Missing required header: {}", name)))
}
}
impl Deref for HeaderValue {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Extension extractor
///
/// Retrieves typed data from request extensions that was inserted by middleware.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::Extension;
///
/// // Middleware inserts user data
/// #[derive(Clone)]
/// struct CurrentUser { id: i64 }
///
/// async fn handler(Extension(user): Extension<CurrentUser>) -> impl IntoResponse {
/// format!("User ID: {}", user.id)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Extension<T>(pub T);
impl<T: Clone + Send + Sync + 'static> FromRequestParts for Extension<T> {
fn from_request_parts(req: &Request) -> Result<Self> {
req.extensions()
.get::<T>()
.cloned()
.map(Extension)
.ok_or_else(|| {
ApiError::internal(format!(
"Extension of type `{}` not found. Did middleware insert it?",
std::any::type_name::<T>()
))
})
}
}
impl<T> Deref for Extension<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Extension<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Client IP address extractor
///
/// Extracts the client IP address from the request. When `trust_proxy` is enabled,
/// it will use the `X-Forwarded-For` header if present.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::ClientIp;
///
/// async fn handler(ClientIp(ip): ClientIp) -> impl IntoResponse {
/// format!("Your IP: {}", ip)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ClientIp(pub std::net::IpAddr);
impl ClientIp {
/// Extract client IP, optionally trusting X-Forwarded-For header
pub fn extract_with_config(req: &Request, trust_proxy: bool) -> Result<Self> {
if trust_proxy {
// Try X-Forwarded-For header first
if let Some(forwarded) = req.headers().get("x-forwarded-for") {
if let Ok(forwarded_str) = forwarded.to_str() {
// X-Forwarded-For can contain multiple IPs, take the first one
if let Some(first_ip) = forwarded_str.split(',').next() {
if let Ok(ip) = first_ip.trim().parse() {
return Ok(ClientIp(ip));
}
}
}
}
}
// Fall back to socket address from extensions (if set by server)
if let Some(addr) = req.extensions().get::<std::net::SocketAddr>() {
return Ok(ClientIp(addr.ip()));
}
// Default to localhost if no IP information available
Ok(ClientIp(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
127, 0, 0, 1,
))))
}
}
impl FromRequestParts for ClientIp {
fn from_request_parts(req: &Request) -> Result<Self> {
// By default, trust proxy headers
Self::extract_with_config(req, true)
}
}
/// Cookies extractor
///
/// Parses and provides access to request cookies from the Cookie header.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::Cookies;
///
/// async fn handler(cookies: Cookies) -> impl IntoResponse {
/// if let Some(session) = cookies.get("session_id") {
/// format!("Session: {}", session.value())
/// } else {
/// "No session cookie".to_string()
/// }
/// }
/// ```
#[cfg(feature = "cookies")]
#[derive(Debug, Clone)]
pub struct Cookies(pub cookie::CookieJar);
#[cfg(feature = "cookies")]
impl Cookies {
/// Get a cookie by name
pub fn get(&self, name: &str) -> Option<&cookie::Cookie<'static>> {
self.0.get(name)
}
/// Iterate over all cookies
pub fn iter(&self) -> impl Iterator<Item = &cookie::Cookie<'static>> {
self.0.iter()
}
/// Check if a cookie exists
pub fn contains(&self, name: &str) -> bool {
self.0.get(name).is_some()
}
}
#[cfg(feature = "cookies")]
impl FromRequestParts for Cookies {
fn from_request_parts(req: &Request) -> Result<Self> {
let mut jar = cookie::CookieJar::new();
if let Some(cookie_header) = req.headers().get(header::COOKIE) {
if let Ok(cookie_str) = cookie_header.to_str() {
// Parse each cookie from the header
for cookie_part in cookie_str.split(';') {
let trimmed = cookie_part.trim();
if !trimmed.is_empty() {
if let Ok(cookie) = cookie::Cookie::parse(trimmed.to_string()) {
jar.add_original(cookie.into_owned());
}
}
}
}
}
Ok(Cookies(jar))
}
}
#[cfg(feature = "cookies")]
impl Deref for Cookies {
type Target = cookie::CookieJar;
fn deref(&self) -> &Self::Target {
&self.0
}
}
// Implement FromRequestParts for common primitive types (path params)
macro_rules! impl_from_request_parts_for_primitives {
($($ty:ty),*) => {
$(
impl FromRequestParts for $ty {
fn from_request_parts(req: &Request) -> Result<Self> {
let Path(value) = Path::<$ty>::from_request_parts(req)?;
Ok(value)
}
}
)*
};
}
impl_from_request_parts_for_primitives!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool, String
);
// OperationModifier implementations for extractors
use rustapi_openapi::{
MediaType, Operation, OperationModifier, Parameter, RequestBody, ResponseModifier, ResponseSpec,
};
// ValidatedJson - Adds request body
impl<T: RustApiSchema> OperationModifier for ValidatedJson<T> {
fn update_operation(op: &mut Operation) {
let mut ctx = SchemaCtx::new();
let schema_ref = T::schema(&mut ctx);
let mut content = BTreeMap::new();
content.insert(
"application/json".to_string(),
MediaType {
schema: Some(schema_ref),
example: None,
},
);
op.request_body = Some(RequestBody {
description: None,
required: Some(true),
content,
});
// Add 422 Validation Error response
let mut responses_content = BTreeMap::new();
responses_content.insert(
"application/json".to_string(),
MediaType {
schema: Some(SchemaRef::Ref {
reference: "#/components/schemas/ValidationErrorSchema".to_string(),