1use crate::extract::Request;
2use crate::extract::{rejection::*, FromRequest, RawForm};
3use axum_core::response::{IntoResponse, IntoResponseFailed, Response};
4use axum_core::RequestExt;
5use http::header::CONTENT_TYPE;
6use http::StatusCode;
7use serde_core::{de::DeserializeOwned, Serialize};
8
9#[cfg_attr(docsrs, doc(cfg(feature = "form")))]
69#[derive(Debug, Clone, Copy, Default)]
70#[must_use]
71pub struct Form<T>(pub T);
72
73impl<T, S> FromRequest<S> for Form<T>
74where
75 T: DeserializeOwned,
76 S: Send + Sync,
77{
78 type Rejection = FormRejection;
79
80 async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
81 let is_get_or_head =
82 req.method() == http::Method::GET || req.method() == http::Method::HEAD;
83
84 match req.extract().await {
85 Ok(RawForm(bytes)) => {
86 let deserializer =
87 || serde_html_form::Deserializer::new(form_urlencoded::parse(&bytes));
88 let value = crate::util::deserialize_with_error_path(deserializer).map_err(
89 |err| -> FormRejection {
90 if is_get_or_head {
91 FailedToDeserializeForm::from_err(err).into()
92 } else {
93 FailedToDeserializeFormBody::from_err(err).into()
94 }
95 },
96 )?;
97 Ok(Self(value))
98 }
99 Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)),
100 Err(RawFormRejection::InvalidFormContentType(r)) => {
101 Err(FormRejection::InvalidFormContentType(r))
102 }
103 }
104 }
105}
106
107impl<T> IntoResponse for Form<T>
108where
109 T: Serialize,
110{
111 fn into_response(self) -> Response {
112 fn make_response(ser_result: Result<String, serde_html_form::ser::Error>) -> Response {
114 match ser_result {
115 Ok(body) => (
116 [(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())],
117 body,
118 )
119 .into_response(),
120 Err(err) => (
121 StatusCode::INTERNAL_SERVER_ERROR,
122 IntoResponseFailed,
123 err.to_string(),
124 )
125 .into_response(),
126 }
127 }
128
129 make_response(serde_html_form::to_string(&self.0))
130 }
131}
132axum_core::__impl_deref!(Form);
133
134#[cfg(test)]
135mod tests {
136 use crate::{
137 routing::{on, MethodFilter},
138 test_helpers::TestClient,
139 Router,
140 };
141
142 use super::*;
143 use axum_core::body::Body;
144 use http::{Method, Request};
145 use mime::APPLICATION_WWW_FORM_URLENCODED;
146 use serde::{Deserialize, Serialize};
147 use std::fmt::Debug;
148
149 #[derive(Debug, PartialEq, Serialize, Deserialize)]
150 struct Pagination {
151 size: Option<u64>,
152 page: Option<u64>,
153 }
154
155 async fn check_query<T: DeserializeOwned + PartialEq + Debug>(uri: impl AsRef<str>, value: T) {
156 let req = Request::builder()
157 .uri(uri.as_ref())
158 .body(Body::empty())
159 .unwrap();
160 assert_eq!(Form::<T>::from_request(req, &()).await.unwrap().0, value);
161 }
162
163 async fn check_body<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
164 let req = Request::builder()
165 .uri("http://example.com/test")
166 .method(Method::POST)
167 .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())
168 .body(Body::from(serde_html_form::to_string(&value).unwrap()))
169 .unwrap();
170 assert_eq!(Form::<T>::from_request(req, &()).await.unwrap().0, value);
171 }
172
173 #[crate::test]
174 async fn test_form_query() {
175 check_query(
176 "http://example.com/test",
177 Pagination {
178 size: None,
179 page: None,
180 },
181 )
182 .await;
183
184 check_query(
185 "http://example.com/test?size=10",
186 Pagination {
187 size: Some(10),
188 page: None,
189 },
190 )
191 .await;
192
193 check_query(
194 "http://example.com/test?size=10&page=20",
195 Pagination {
196 size: Some(10),
197 page: Some(20),
198 },
199 )
200 .await;
201 }
202
203 #[crate::test]
204 async fn test_form_body() {
205 check_body(Pagination {
206 size: None,
207 page: None,
208 })
209 .await;
210
211 check_body(Pagination {
212 size: Some(10),
213 page: None,
214 })
215 .await;
216
217 check_body(Pagination {
218 size: Some(10),
219 page: Some(20),
220 })
221 .await;
222 }
223
224 #[crate::test]
225 async fn test_incorrect_content_type() {
226 let req = Request::builder()
227 .uri("http://example.com/test")
228 .method(Method::POST)
229 .header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())
230 .body(Body::from(
231 serde_html_form::to_string(&Pagination {
232 size: Some(10),
233 page: None,
234 })
235 .unwrap(),
236 ))
237 .unwrap();
238 assert!(matches!(
239 Form::<Pagination>::from_request(req, &())
240 .await
241 .unwrap_err(),
242 FormRejection::InvalidFormContentType(InvalidFormContentType)
243 ));
244 }
245
246 #[tokio::test]
247 async fn deserialize_error_status_codes() {
248 #[allow(dead_code)]
249 #[derive(Deserialize)]
250 struct Payload {
251 a: i32,
252 }
253
254 let app = Router::new().route(
255 "/",
256 on(
257 MethodFilter::GET.or(MethodFilter::POST),
258 |_: Form<Payload>| async {},
259 ),
260 );
261
262 let client = TestClient::new(app);
263
264 let res = client.get("/?a=false").await;
265 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
266 assert_eq!(
267 res.text().await,
268 "Failed to deserialize form: a: invalid digit found in string"
269 );
270
271 let res = client
272 .post("/")
273 .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())
274 .body("a=false")
275 .await;
276 assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
277 assert_eq!(
278 res.text().await,
279 "Failed to deserialize form body: a: invalid digit found in string"
280 );
281 }
282}