Skip to main content

axum_core/extract/
request_parts.rs

1use super::{rejection::*, FromRequest, FromRequestParts, Request};
2use crate::{body::Body, RequestExt};
3use bytes::{BufMut, Bytes, BytesMut};
4use http::{request::Parts, Extensions, HeaderMap, Method, Uri, Version};
5use http_body_util::BodyExt;
6use std::convert::Infallible;
7
8impl<S> FromRequest<S> for Request
9where
10    S: Send + Sync,
11{
12    type Rejection = Infallible;
13
14    async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> {
15        Ok(req)
16    }
17}
18
19impl<S> FromRequestParts<S> for Method
20where
21    S: Send + Sync,
22{
23    type Rejection = Infallible;
24
25    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
26        Ok(parts.method.clone())
27    }
28}
29
30impl<S> FromRequestParts<S> for Uri
31where
32    S: Send + Sync,
33{
34    type Rejection = Infallible;
35
36    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
37        Ok(parts.uri.clone())
38    }
39}
40
41impl<S> FromRequestParts<S> for Version
42where
43    S: Send + Sync,
44{
45    type Rejection = Infallible;
46
47    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
48        Ok(parts.version)
49    }
50}
51
52/// Clone the headers from the request.
53///
54/// Prefer using [`TypedHeader`] to extract only the headers you need.
55///
56/// [`TypedHeader`]: https://docs.rs/axum-extra/0.10/axum_extra/struct.TypedHeader.html
57impl<S> FromRequestParts<S> for HeaderMap
58where
59    S: Send + Sync,
60{
61    type Rejection = Infallible;
62
63    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
64        Ok(parts.headers.clone())
65    }
66}
67
68#[diagnostic::do_not_recommend] // pretty niche impl
69impl<S> FromRequest<S> for BytesMut
70where
71    S: Send + Sync,
72{
73    type Rejection = BytesRejection;
74
75    async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> {
76        let mut body = req.into_limited_body();
77        #[allow(clippy::use_self)]
78        let mut bytes = BytesMut::new();
79        body_to_bytes_mut(&mut body, &mut bytes).await?;
80        Ok(bytes)
81    }
82}
83
84async fn body_to_bytes_mut(body: &mut Body, bytes: &mut BytesMut) -> Result<(), BytesRejection> {
85    while let Some(frame) = body
86        .frame()
87        .await
88        .transpose()
89        .map_err(FailedToBufferBody::from_err)?
90    {
91        let Ok(data) = frame.into_data() else {
92            // Match `Bytes` by ignoring non-data frames until the body ends.
93            continue;
94        };
95        bytes.put(data);
96    }
97
98    Ok(())
99}
100
101impl<S> FromRequest<S> for Bytes
102where
103    S: Send + Sync,
104{
105    type Rejection = BytesRejection;
106
107    async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> {
108        let bytes = req
109            .into_limited_body()
110            .collect()
111            .await
112            .map_err(FailedToBufferBody::from_err)?
113            .to_bytes();
114
115        Ok(bytes)
116    }
117}
118
119impl<S> FromRequest<S> for String
120where
121    S: Send + Sync,
122{
123    type Rejection = StringRejection;
124
125    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
126        let bytes = Bytes::from_request(req, state)
127            .await
128            .map_err(|err| match err {
129                BytesRejection::FailedToBufferBody(inner) => {
130                    StringRejection::FailedToBufferBody(inner)
131                }
132            })?;
133
134        #[allow(clippy::use_self)]
135        let string = String::from_utf8(bytes.into()).map_err(InvalidUtf8::from_err)?;
136
137        Ok(string)
138    }
139}
140
141#[diagnostic::do_not_recommend] // pretty niche impl
142impl<S> FromRequestParts<S> for Parts
143where
144    S: Send + Sync,
145{
146    type Rejection = Infallible;
147
148    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
149        Ok(parts.clone())
150    }
151}
152
153#[diagnostic::do_not_recommend] // pretty niche impl
154impl<S> FromRequestParts<S> for Extensions
155where
156    S: Send + Sync,
157{
158    type Rejection = Infallible;
159
160    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
161        Ok(parts.extensions.clone())
162    }
163}
164
165impl<S> FromRequest<S> for Body
166where
167    S: Send + Sync,
168{
169    type Rejection = Infallible;
170
171    async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> {
172        Ok(req.into_body())
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use axum::{extract::Extension, routing::get, test_helpers::*, Router};
179    use http::{Method, StatusCode};
180
181    #[crate::test]
182    async fn extract_request_parts() {
183        #[derive(Clone)]
184        struct Ext;
185
186        async fn handler(parts: http::request::Parts) {
187            assert_eq!(parts.method, Method::GET);
188            assert_eq!(parts.uri, "/");
189            assert_eq!(parts.version, http::Version::HTTP_11);
190            assert_eq!(parts.headers["x-foo"], "123");
191            parts.extensions.get::<Ext>().unwrap();
192        }
193
194        let client = TestClient::new(Router::new().route("/", get(handler)).layer(Extension(Ext)));
195
196        let res = client.get("/").header("x-foo", "123").await;
197        assert_eq!(res.status(), StatusCode::OK);
198    }
199}