tako_rs_extractors/header_map.rs
1//! Header extraction from HTTP requests.
2//!
3//! This module provides the [`HeaderMap`](crate::header_map::HeaderMap) extractor for accessing HTTP headers from
4//! incoming requests. It wraps a reference to the headers, allowing efficient access
5//! to header values without copying the underlying data.
6//!
7//! # Examples
8//!
9//! ```rust
10//! use tako::extractors::header_map::HeaderMap;
11//! use tako::types::Request;
12//!
13//! async fn handle_headers(HeaderMap(headers): HeaderMap<'_>) {
14//! // Check for specific headers
15//! if let Some(user_agent) = headers.get("user-agent") {
16//! println!("User-Agent: {:?}", user_agent);
17//! }
18//!
19//! // Iterate over all headers
20//! for (name, value) in headers.iter() {
21//! println!("{}: {:?}", name, value);
22//! }
23//! }
24//! ```
25
26use std::convert::Infallible;
27
28use http::request::Parts;
29use tako_rs_core::extractors::FromRequest;
30use tako_rs_core::extractors::FromRequestParts;
31use tako_rs_core::types::Request;
32
33/// Header map extractor that provides access to HTTP request headers.
34///
35/// This extractor wraps a reference to the headers of a request, providing
36/// efficient access to header values without copying the underlying data.
37/// It can be used to inspect, validate, or extract information from HTTP headers.
38///
39/// # Examples
40///
41/// ```rust
42/// use tako::extractors::header_map::HeaderMap;
43/// use tako::types::Request;
44///
45/// async fn handler(HeaderMap(headers): HeaderMap<'_>) {
46/// // Get authorization header
47/// if let Some(auth) = headers.get("authorization") {
48/// if let Ok(auth_str) = auth.to_str() {
49/// println!("Authorization: {}", auth_str);
50/// }
51/// }
52///
53/// // Check content type
54/// if let Some(content_type) = headers.get("content-type") {
55/// println!("Content-Type: {:?}", content_type);
56/// }
57/// }
58/// ```
59#[doc(alias = "headers")]
60#[derive(Clone)]
61pub struct HeaderMap(pub http::HeaderMap);
62
63impl<'a> FromRequest<'a> for HeaderMap {
64 type Error = Infallible;
65
66 fn from_request(
67 req: &'a mut Request,
68 ) -> impl core::future::Future<Output = core::result::Result<Self, Self::Error>> + Send + 'a {
69 futures_util::future::ready(Ok(HeaderMap(req.headers().clone())))
70 }
71}
72
73impl<'a> FromRequestParts<'a> for HeaderMap {
74 type Error = Infallible;
75
76 fn from_request_parts(
77 parts: &'a mut Parts,
78 ) -> impl core::future::Future<Output = core::result::Result<Self, Self::Error>> + Send + 'a {
79 futures_util::future::ready(Ok(HeaderMap(parts.headers.clone())))
80 }
81}