reinhardt-http 0.1.0-rc.29

HTTP primitives, request and response handling for Reinhardt
Documentation
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
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
mod body;
mod methods;
mod params;

use crate::extensions::Extensions;
use crate::path_params::PathParams;
use bytes::Bytes;
use hyper::{HeaderMap, Method, Uri, Version};
#[cfg(feature = "parsers")]
use reinhardt_core::parsers::parser::{ParsedData, Parser};
use std::collections::HashMap;
use std::collections::HashSet;
use std::net::{IpAddr, SocketAddr};
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};

/// Configuration for trusted proxy IPs.
///
/// Only proxy headers (X-Forwarded-For, X-Real-IP, X-Forwarded-Proto) from
/// these IP addresses will be trusted. By default, no proxies are trusted
/// and the actual connection information is used.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedProxies {
	/// Set of trusted proxy IP addresses.
	/// Only requests originating from these IPs will have their proxy headers honored.
	trusted_ips: HashSet<IpAddr>,
}

impl TrustedProxies {
	/// Create with no trusted proxies (default, most secure).
	pub fn none() -> Self {
		Self {
			trusted_ips: HashSet::new(),
		}
	}

	/// Create with a set of trusted proxy IPs.
	pub fn new(ips: impl IntoIterator<Item = IpAddr>) -> Self {
		Self {
			trusted_ips: ips.into_iter().collect(),
		}
	}

	/// Check if the given address is a trusted proxy.
	pub fn is_trusted(&self, addr: &IpAddr) -> bool {
		self.trusted_ips.contains(addr)
	}

	/// Check if any proxies are configured.
	pub fn has_trusted_proxies(&self) -> bool {
		!self.trusted_ips.is_empty()
	}
}

/// HTTP Request representation
pub struct Request {
	/// The HTTP method (GET, POST, PUT, etc.).
	pub method: Method,
	/// The request URI (path and query string).
	pub uri: Uri,
	/// The HTTP protocol version.
	pub version: Version,
	/// The request headers.
	pub headers: HeaderMap,
	body: Bytes,
	/// Path parameters extracted from the URL pattern.
	///
	/// Stored in URL pattern declaration order (see [`PathParams`]).
	pub path_params: PathParams,
	/// Query string parameters parsed from the URI.
	pub query_params: HashMap<String, String>,
	/// Indicates if this request came over HTTPS
	pub is_secure: bool,
	/// Remote address of the client (if available)
	pub remote_addr: Option<SocketAddr>,
	/// Parsers for request body
	#[cfg(feature = "parsers")]
	parsers: Vec<Box<dyn Parser>>,
	/// Cached parsed data (lazy parsing)
	#[cfg(feature = "parsers")]
	parsed_data: Arc<Mutex<Option<ParsedData>>>,
	/// Whether the body has been consumed
	body_consumed: Arc<AtomicBool>,
	/// Extensions for storing arbitrary typed data
	pub extensions: Extensions,
}

/// Builder for constructing `Request` instances.
///
/// Provides a fluent API for building HTTP requests with optional parameters.
///
/// # Examples
///
/// ```
/// use reinhardt_http::Request;
/// use hyper::Method;
///
/// let request = Request::builder()
///     .method(Method::GET)
///     .uri("/api/users?page=1")
///     .build()
///     .unwrap();
///
/// assert_eq!(request.method, Method::GET);
/// assert_eq!(request.path(), "/api/users");
/// assert_eq!(request.query_params.get("page"), Some(&"1".to_string()));
/// ```
pub struct RequestBuilder {
	method: Method,
	uri: Option<Uri>,
	version: Version,
	headers: HeaderMap,
	body: Bytes,
	is_secure: bool,
	remote_addr: Option<SocketAddr>,
	path_params: PathParams,
	/// Captured error from invalid URI
	uri_error: Option<String>,
	/// Captured error from invalid header value
	header_error: Option<String>,
	#[cfg(feature = "parsers")]
	parsers: Vec<Box<dyn Parser>>,
}

impl Default for RequestBuilder {
	fn default() -> Self {
		Self {
			method: Method::GET,
			uri: None,
			version: Version::HTTP_11,
			headers: HeaderMap::new(),
			body: Bytes::new(),
			is_secure: false,
			remote_addr: None,
			path_params: PathParams::new(),
			uri_error: None,
			header_error: None,
			#[cfg(feature = "parsers")]
			parsers: Vec::new(),
		}
	}
}

impl RequestBuilder {
	/// Set the HTTP method.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/api/users")
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.method, Method::POST);
	/// ```
	pub fn method(mut self, method: Method) -> Self {
		self.method = method;
		self
	}

	/// Set the request URI.
	///
	/// Accepts either a `&str` or `Uri`. Query parameters will be automatically parsed.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users?page=1&limit=10")
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.path(), "/api/users");
	/// assert_eq!(request.query_params.get("page"), Some(&"1".to_string()));
	/// assert_eq!(request.query_params.get("limit"), Some(&"10".to_string()));
	/// ```
	pub fn uri<T>(mut self, uri: T) -> Self
	where
		T: TryInto<Uri>,
		T::Error: std::fmt::Display,
	{
		match uri.try_into() {
			Ok(uri) => {
				self.uri = Some(uri);
			}
			Err(e) => {
				self.uri_error = Some(format!("Invalid URI: {}", e));
			}
		}
		self
	}

	/// Set the HTTP version.
	///
	/// Defaults to HTTP/1.1 if not specified.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version};
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users")
	///     .version(Version::HTTP_2)
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.version, Version::HTTP_2);
	/// ```
	pub fn version(mut self, version: Version) -> Self {
		self.version = version;
		self
	}

	/// Set the request headers.
	///
	/// Replaces all existing headers.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, HeaderMap, header};
	///
	/// let mut headers = HeaderMap::new();
	/// headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/api/users")
	///     .headers(headers.clone())
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.headers.get(header::CONTENT_TYPE).unwrap(), "application/json");
	/// ```
	pub fn headers(mut self, headers: HeaderMap) -> Self {
		self.headers = headers;
		self
	}

	/// Add a single header to the request.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, header};
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/api/users")
	///     .header(header::CONTENT_TYPE, "application/json")
	///     .header(header::AUTHORIZATION, "Bearer token123")
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.headers.get(header::CONTENT_TYPE).unwrap(), "application/json");
	/// assert_eq!(request.headers.get(header::AUTHORIZATION).unwrap(), "Bearer token123");
	/// ```
	pub fn header<K, V>(mut self, key: K, value: V) -> Self
	where
		K: hyper::header::IntoHeaderName,
		V: TryInto<hyper::header::HeaderValue>,
		V::Error: std::fmt::Display,
	{
		match value.try_into() {
			Ok(val) => {
				self.headers.insert(key, val);
			}
			Err(e) => {
				self.header_error = Some(format!("Invalid header value: {}", e));
			}
		}
		self
	}

	/// Set the request body.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	/// use bytes::Bytes;
	///
	/// let body = Bytes::from(r#"{"name":"Alice"}"#);
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/api/users")
	///     .body(body.clone())
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.body(), &body);
	/// ```
	pub fn body(mut self, body: Bytes) -> Self {
		self.body = body;
		self
	}

	/// Set whether the request is secure (HTTPS).
	///
	/// Defaults to `false` if not specified.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .secure(true)
	///     .build()
	///     .unwrap();
	///
	/// assert!(request.is_secure());
	/// assert_eq!(request.scheme(), "https");
	/// ```
	pub fn secure(mut self, is_secure: bool) -> Self {
		self.is_secure = is_secure;
		self
	}

	/// Set the remote address of the client.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	/// use std::net::{SocketAddr, IpAddr, Ipv4Addr};
	///
	/// let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .remote_addr(addr)
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.remote_addr, Some(addr));
	/// ```
	pub fn remote_addr(mut self, addr: SocketAddr) -> Self {
		self.remote_addr = Some(addr);
		self
	}

	/// Add a parser to the request.
	///
	/// Parsers are used to parse the request body into specific formats.
	/// The parser will be boxed internally.
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/api/users")
	///     .parser(JsonParser::new())
	///     .build()
	///     .unwrap();
	/// ```
	#[cfg(feature = "parsers")]
	pub fn parser<P: Parser + 'static>(mut self, parser: P) -> Self {
		self.parsers.push(Box::new(parser));
		self
	}

	/// Set path parameters (used for testing views without router).
	///
	/// This is primarily useful in test environments where you need to simulate
	/// path parameters that would normally be extracted by the router. Accepts
	/// any value that can be converted into [`PathParams`], including a
	/// `HashMap<String, String>` (note: converting from a `HashMap` does not
	/// preserve ordering — pass a `Vec<(String, String)>` or [`PathParams`]
	/// directly when ordering matters).
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	/// use std::collections::HashMap;
	///
	/// let mut params = HashMap::new();
	/// params.insert("id".to_string(), "42".to_string());
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users/42")
	///     .path_params(params)
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.path_params.get("id"), Some(&"42".to_string()));
	/// ```
	pub fn path_params(mut self, params: impl Into<PathParams>) -> Self {
		self.path_params = params.into();
		self
	}

	/// Build the final `Request` instance.
	///
	/// Returns an error if the URI is missing.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users")
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.method, Method::GET);
	/// assert_eq!(request.path(), "/api/users");
	/// ```
	pub fn build(self) -> Result<Request, String> {
		// Report captured errors from builder methods
		if let Some(err) = self.uri_error {
			return Err(err);
		}
		if let Some(err) = self.header_error {
			return Err(err);
		}
		let uri = self.uri.ok_or_else(|| "URI is required".to_string())?;
		let query_params = Request::parse_query_params(&uri);

		Ok(Request {
			method: self.method,
			uri,
			version: self.version,
			headers: self.headers,
			body: self.body,
			path_params: self.path_params,
			query_params,
			is_secure: self.is_secure,
			remote_addr: self.remote_addr,
			#[cfg(feature = "parsers")]
			parsers: self.parsers,
			#[cfg(feature = "parsers")]
			parsed_data: Arc::new(Mutex::new(None)),
			body_consumed: Arc::new(AtomicBool::new(false)),
			extensions: Extensions::new(),
		})
	}
}

impl Request {
	/// Create a new `RequestBuilder`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users")
	///     .build()
	///     .unwrap();
	///
	/// assert_eq!(request.method, Method::GET);
	/// ```
	pub fn builder() -> RequestBuilder {
		RequestBuilder::default()
	}

	/// Set the DI context for this request (used by routers with dependency injection)
	///
	/// This method stores the DI context in the request's extensions,
	/// allowing handlers to access dependency injection services.
	///
	/// The context will be wrapped in an Arc internally for efficient sharing.
	/// The DI context type is generic to avoid circular dependencies.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// # struct DummyDiContext;
	/// let mut request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .build()
	///     .unwrap();
	///
	/// let di_ctx = DummyDiContext;
	/// request.set_di_context(di_ctx);
	/// ```
	pub fn set_di_context<T: Send + Sync + 'static>(&mut self, ctx: T) {
		self.extensions.insert(Arc::new(ctx));
	}

	/// Get the DI context from this request
	///
	/// Returns `None` if no DI context was set.
	///
	/// The DI context type is generic to avoid circular dependencies.
	/// Returns a reference to the context.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_http::Request;
	/// use hyper::Method;
	///
	/// # struct DummyDiContext;
	/// let mut request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .build()
	///     .unwrap();
	///
	/// let di_ctx = DummyDiContext;
	/// request.set_di_context(di_ctx);
	///
	/// let ctx = request.get_di_context::<DummyDiContext>();
	/// assert!(ctx.is_some());
	/// ```
	pub fn get_di_context<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
		self.extensions.get::<Arc<T>>()
	}

	/// Extract Bearer token from Authorization header
	///
	/// Extracts JWT or other bearer tokens from the Authorization header.
	/// Returns `None` if the header is missing or not in "Bearer `<token>`" format.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap, header};
	/// use bytes::Bytes;
	///
	/// let mut headers = HeaderMap::new();
	/// headers.insert(
	///     header::AUTHORIZATION,
	///     "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9".parse().unwrap()
	/// );
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(headers)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let token = request.extract_bearer_token();
	/// assert_eq!(token, Some("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9".to_string()));
	/// ```
	///
	/// # Missing or invalid header
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap};
	/// use bytes::Bytes;
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let token = request.extract_bearer_token();
	/// assert_eq!(token, None);
	/// ```
	pub fn extract_bearer_token(&self) -> Option<String> {
		self.headers
			.get(hyper::header::AUTHORIZATION)
			.and_then(|value| value.to_str().ok())
			.and_then(|auth_str| auth_str.strip_prefix("Bearer ").map(|s| s.to_string()))
	}

	/// Get a specific header value from the request
	///
	/// Returns `None` if the header is missing or cannot be converted to a string.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap, header};
	/// use bytes::Bytes;
	///
	/// let mut headers = HeaderMap::new();
	/// headers.insert(
	///     header::USER_AGENT,
	///     "Mozilla/5.0".parse().unwrap()
	/// );
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(headers)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let user_agent = request.get_header("user-agent");
	/// assert_eq!(user_agent, Some("Mozilla/5.0".to_string()));
	/// ```
	///
	/// # Missing header
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap};
	/// use bytes::Bytes;
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let header = request.get_header("x-custom-header");
	/// assert_eq!(header, None);
	/// ```
	pub fn get_header(&self, name: &str) -> Option<String> {
		self.headers
			.get(name)
			.and_then(|value| value.to_str().ok())
			.map(|s| s.to_string())
	}

	/// Extract client IP address from the request
	///
	/// Only trusts proxy headers (X-Forwarded-For, X-Real-IP) when the request
	/// originates from a configured trusted proxy. Without trusted proxies,
	/// falls back to the actual connection address.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::{Request, TrustedProxies};
	/// use hyper::{Method, Version, HeaderMap, header};
	/// use bytes::Bytes;
	/// use std::net::{SocketAddr, IpAddr, Ipv4Addr};
	///
	/// let proxy_ip = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
	/// let mut headers = HeaderMap::new();
	/// headers.insert(
	///     header::HeaderName::from_static("x-forwarded-for"),
	///     "203.0.113.1, 198.51.100.1".parse().unwrap()
	/// );
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(headers)
	///     .remote_addr(SocketAddr::new(proxy_ip, 8080))
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// // Configure trusted proxies to honor X-Forwarded-For
	/// request.set_trusted_proxies(TrustedProxies::new(vec![proxy_ip]));
	///
	/// let ip = request.get_client_ip();
	/// assert_eq!(ip, Some("203.0.113.1".parse().unwrap()));
	/// ```
	///
	/// # No trusted proxy, fallback to remote_addr
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap};
	/// use bytes::Bytes;
	/// use std::net::{SocketAddr, IpAddr, Ipv4Addr};
	///
	/// let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .remote_addr(addr)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let ip = request.get_client_ip();
	/// assert_eq!(ip, Some(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))));
	/// ```
	pub fn get_client_ip(&self) -> Option<std::net::IpAddr> {
		// Only trust proxy headers if the request comes from a configured trusted proxy
		if self.is_from_trusted_proxy() {
			// Try X-Forwarded-For header first (common in proxy setups)
			if let Some(forwarded) = self.get_header("x-forwarded-for") {
				// X-Forwarded-For can contain multiple IPs, take the first one
				if let Some(first_ip) = forwarded.split(',').next()
					&& let Ok(ip) = first_ip.trim().parse()
				{
					return Some(ip);
				}
			}

			// Try X-Real-IP header
			if let Some(real_ip) = self.get_header("x-real-ip")
				&& let Ok(ip) = real_ip.parse()
			{
				return Some(ip);
			}
		}

		// Fallback to remote_addr (actual connection info)
		self.remote_addr.map(|addr| addr.ip())
	}

	/// Check if the request originates from a trusted proxy.
	///
	/// Returns `true` only if [`TrustedProxies`] are configured (via
	/// [`set_trusted_proxies`](Self::set_trusted_proxies)) **and** the
	/// remote address of the connection is contained in the trusted set.
	///
	/// # Security
	///
	/// This method gates whether proxy-forwarded headers (e.g.
	/// `X-Forwarded-For`, `X-Forwarded-Proto`) should be honoured.
	/// Trusting headers from a non-proxy source allows clients to spoof
	/// their IP address or protocol, which can bypass IP-based access
	/// controls and HTTPS enforcement.
	///
	/// **Callers must ensure that [`TrustedProxies`] is configured only
	/// with IP addresses of reverse proxies actually deployed in front
	/// of the application.** Misconfiguration (e.g. trusting `0.0.0.0/0`)
	/// re-introduces header-spoofing vulnerabilities.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use reinhardt_http::TrustedProxies;
	/// use bytes::Bytes;
	/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
	/// use hyper::Method;
	///
	/// let proxy_ip: IpAddr = Ipv4Addr::new(10, 0, 0, 1).into();
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .remote_addr(SocketAddr::new(proxy_ip, 8080))
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	/// request.set_trusted_proxies(TrustedProxies::new(vec![proxy_ip]));
	///
	/// assert!(request.is_from_trusted_proxy());
	/// ```
	pub fn is_from_trusted_proxy(&self) -> bool {
		if let Some(trusted) = self.extensions.get::<TrustedProxies>()
			&& let Some(addr) = self.remote_addr
		{
			return trusted.is_trusted(&addr.ip());
		}
		false
	}

	/// Set trusted proxy configuration for this request.
	///
	/// This is typically called by the server/middleware layer to configure
	/// which proxy IPs are trusted for header forwarding.
	pub fn set_trusted_proxies(&self, proxies: TrustedProxies) {
		self.extensions.insert(proxies);
	}

	/// Validate Content-Type header
	///
	/// Checks if the Content-Type header matches the expected value.
	/// Returns an error if the header is missing or doesn't match.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap, header};
	/// use bytes::Bytes;
	///
	/// let mut headers = HeaderMap::new();
	/// headers.insert(
	///     header::CONTENT_TYPE,
	///     "application/json".parse().unwrap()
	/// );
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(headers)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// assert!(request.validate_content_type("application/json").is_ok());
	/// ```
	///
	/// # Content-Type mismatch
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap, header};
	/// use bytes::Bytes;
	///
	/// let mut headers = HeaderMap::new();
	/// headers.insert(
	///     header::CONTENT_TYPE,
	///     "text/plain".parse().unwrap()
	/// );
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(headers)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let result = request.validate_content_type("application/json");
	/// assert!(result.is_err());
	/// ```
	///
	/// # Missing Content-Type header
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap};
	/// use bytes::Bytes;
	///
	/// let request = Request::builder()
	///     .method(Method::POST)
	///     .uri("/")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let result = request.validate_content_type("application/json");
	/// assert!(result.is_err());
	/// ```
	pub fn validate_content_type(&self, expected: &str) -> crate::Result<()> {
		match self.get_header("content-type") {
			Some(content_type) if content_type.starts_with(expected) => Ok(()),
			Some(content_type) => Err(crate::Error::Http(format!(
				"Invalid Content-Type: expected '{}', got '{}'",
				expected, content_type
			))),
			None => Err(crate::Error::Http(
				"Missing Content-Type header".to_string(),
			)),
		}
	}

	/// Parse query parameters into typed struct
	///
	/// Deserializes query string parameters into the specified type `T`.
	/// Returns an error if deserialization fails.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap};
	/// use bytes::Bytes;
	/// use serde::Deserialize;
	///
	/// #[derive(Deserialize, Debug, PartialEq)]
	/// struct Pagination {
	///     page: u32,
	///     limit: u32,
	/// }
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users?page=2&limit=10")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let params: Pagination = request.query_as().unwrap();
	/// assert_eq!(params, Pagination { page: 2, limit: 10 });
	/// ```
	///
	/// # Type mismatch error
	///
	/// ```
	/// use reinhardt_http::Request;
	/// use hyper::{Method, Version, HeaderMap};
	/// use bytes::Bytes;
	/// use serde::Deserialize;
	///
	/// #[derive(Deserialize)]
	/// struct Pagination {
	///     page: u32,
	///     limit: u32,
	/// }
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/users?page=invalid")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let result: Result<Pagination, _> = request.query_as();
	/// assert!(result.is_err());
	/// ```
	pub fn query_as<T: serde::de::DeserializeOwned>(&self) -> crate::Result<T> {
		// Convert HashMap<String, String> to Vec<(String, String)> for serde_urlencoded
		let params: Vec<(String, String)> = self
			.query_params
			.iter()
			.map(|(k, v)| (k.clone(), v.clone()))
			.collect();

		let encoded = serde_urlencoded::to_string(&params)
			.map_err(|e| crate::Error::Http(format!("Failed to encode query parameters: {}", e)))?;
		serde_urlencoded::from_str(&encoded)
			.map_err(|e| crate::Error::Http(format!("Failed to parse query parameters: {}", e)))
	}

	/// Creates a lightweight copy of this request for dependency injection.
	///
	/// The clone shares the same extensions store (via internal `Arc`),
	/// so `AuthState` and other extensions set on the original request
	/// are accessible in the clone. Body and parsers are not copied
	/// as they are not needed for DI resolution.
	pub fn clone_for_di(&self) -> Self {
		Request {
			method: self.method.clone(),
			uri: self.uri.clone(),
			version: self.version,
			headers: self.headers.clone(),
			body: Bytes::new(),
			path_params: self.path_params.clone(),
			query_params: self.query_params.clone(),
			is_secure: self.is_secure,
			remote_addr: self.remote_addr,
			#[cfg(feature = "parsers")]
			parsers: Vec::new(),
			#[cfg(feature = "parsers")]
			parsed_data: Arc::new(Mutex::new(None)),
			body_consumed: Arc::new(AtomicBool::new(false)),
			extensions: self.extensions.clone(),
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, Version, header};
	use rstest::rstest;

	#[rstest]
	fn test_extract_bearer_token() {
		let mut headers = HeaderMap::new();
		headers.insert(
			header::AUTHORIZATION,
			"Bearer test_token_123".parse().unwrap(),
		);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();

		let token = request.extract_bearer_token();
		assert_eq!(token, Some("test_token_123".to_string()));
	}

	#[rstest]
	fn test_extract_bearer_token_missing() {
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let token = request.extract_bearer_token();
		assert_eq!(token, None);
	}

	#[rstest]
	fn test_get_header() {
		let mut headers = HeaderMap::new();
		headers.insert(header::USER_AGENT, "TestClient/1.0".parse().unwrap());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();

		let user_agent = request.get_header("user-agent");
		assert_eq!(user_agent, Some("TestClient/1.0".to_string()));
	}

	#[rstest]
	fn test_get_header_missing() {
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let header = request.get_header("x-custom-header");
		assert_eq!(header, None);
	}

	#[rstest]
	fn test_get_client_ip_forwarded_for_with_trusted_proxy() {
		// Arrange
		let proxy_ip: std::net::IpAddr = "10.0.0.254".parse().unwrap();
		let mut headers = HeaderMap::new();
		headers.insert(
			header::HeaderName::from_static("x-forwarded-for"),
			"192.168.1.1, 10.0.0.1".parse().unwrap(),
		);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.remote_addr(std::net::SocketAddr::new(proxy_ip, 8080))
			.build()
			.unwrap();

		// Configure trusted proxies
		request.set_trusted_proxies(TrustedProxies::new(vec![proxy_ip]));

		// Act & Assert
		let ip = request.get_client_ip();
		assert_eq!(ip, Some("192.168.1.1".parse().unwrap()));
	}

	#[rstest]
	fn test_get_client_ip_forwarded_for_without_trusted_proxy() {
		// Arrange - proxy headers present but no trusted proxy configured
		let mut headers = HeaderMap::new();
		headers.insert(
			header::HeaderName::from_static("x-forwarded-for"),
			"192.168.1.1, 10.0.0.1".parse().unwrap(),
		);

		let remote_ip: std::net::IpAddr = "10.0.0.254".parse().unwrap();
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.remote_addr(std::net::SocketAddr::new(remote_ip, 8080))
			.build()
			.unwrap();

		// Act - no trusted proxies, should use remote_addr
		let ip = request.get_client_ip();
		assert_eq!(ip, Some(remote_ip));
	}

	#[rstest]
	fn test_get_client_ip_real_ip_with_trusted_proxy() {
		// Arrange
		let proxy_ip: std::net::IpAddr = "10.0.0.254".parse().unwrap();
		let mut headers = HeaderMap::new();
		headers.insert(
			header::HeaderName::from_static("x-real-ip"),
			"203.0.113.5".parse().unwrap(),
		);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.remote_addr(std::net::SocketAddr::new(proxy_ip, 8080))
			.build()
			.unwrap();

		request.set_trusted_proxies(TrustedProxies::new(vec![proxy_ip]));

		// Act & Assert
		let ip = request.get_client_ip();
		assert_eq!(ip, Some("203.0.113.5".parse().unwrap()));
	}

	#[rstest]
	fn test_get_client_ip_none() {
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let ip = request.get_client_ip();
		assert_eq!(ip, None);
	}

	#[rstest]
	fn test_validate_content_type_valid() {
		let mut headers = HeaderMap::new();
		headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());

		let request = Request::builder()
			.method(Method::POST)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();

		assert!(request.validate_content_type("application/json").is_ok());
	}

	#[rstest]
	fn test_validate_content_type_invalid() {
		let mut headers = HeaderMap::new();
		headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());

		let request = Request::builder()
			.method(Method::POST)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();

		assert!(request.validate_content_type("application/json").is_err());
	}

	#[rstest]
	fn test_validate_content_type_missing() {
		let request = Request::builder()
			.method(Method::POST)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		assert!(request.validate_content_type("application/json").is_err());
	}

	#[rstest]
	fn test_clone_for_di_shares_extensions() {
		// Arrange
		let request = Request::builder()
			.method(Method::POST)
			.uri("/api/users/42?page=1")
			.version(Version::HTTP_11)
			.header(header::CONTENT_TYPE, "application/json")
			.body(Bytes::from("request body"))
			.build()
			.unwrap();

		request.extensions.insert(42u32);

		// Act
		let cloned = request.clone_for_di();

		// Assert - extensions are shared (same Arc backing store)
		assert_eq!(cloned.extensions.get::<u32>(), Some(42));

		// Verify metadata is preserved
		assert_eq!(cloned.method, Method::POST);
		assert_eq!(cloned.uri.path(), "/api/users/42");
		assert_eq!(cloned.version, Version::HTTP_11);
		assert!(cloned.headers.contains_key(header::CONTENT_TYPE));
		assert_eq!(cloned.query_params.get("page"), Some(&"1".to_string()));

		// Body should be empty (not needed for DI)
		assert!(cloned.body().is_empty());
	}

	#[rstest]
	fn test_clone_for_di_shares_extensions_bidirectionally() {
		// Arrange
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.build()
			.unwrap();

		let cloned = request.clone_for_di();

		// Act - insert into cloned extensions
		cloned.extensions.insert("from_clone".to_string());

		// Assert - original also sees it (shared backing store)
		assert_eq!(
			request.extensions.get::<String>(),
			Some("from_clone".to_string())
		);
	}
}