1use axum_core::extract::{FromRequest, Request};
2use bytes::Bytes;
3use http::Method;
4
5use super::{
6 has_content_type,
7 rejection::{InvalidFormContentType, RawFormRejection},
8};
9
10#[derive(Debug)]
30pub struct RawForm(pub Bytes);
31
32impl<S> FromRequest<S> for RawForm
33where
34 S: Send + Sync,
35{
36 type Rejection = RawFormRejection;
37
38 async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
39 if req.method() == Method::GET || req.method() == Method::HEAD {
40 if let Some(query) = req.uri().query() {
41 return Ok(Self(Bytes::copy_from_slice(query.as_bytes())));
42 }
43
44 Ok(Self(Bytes::new()))
45 } else {
46 if !has_content_type(req.headers(), &mime::APPLICATION_WWW_FORM_URLENCODED) {
47 return Err(InvalidFormContentType.into());
48 }
49
50 Ok(Self(Bytes::from_request(req, state).await?))
51 }
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use axum_core::body::Body;
58 use http::{header::CONTENT_TYPE, Method, Request};
59
60 use super::{InvalidFormContentType, RawForm, RawFormRejection};
61
62 use crate::extract::FromRequest;
63
64 async fn check_query(uri: &str, value: &[u8]) {
65 let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
66
67 assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, value);
68 }
69
70 async fn check_head_query(uri: &str, value: &[u8]) {
71 let req = Request::builder()
72 .method(Method::HEAD)
73 .uri(uri)
74 .body(Body::empty())
75 .unwrap();
76
77 assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, value);
78 }
79
80 async fn check_body(body: &'static [u8]) {
81 let req = Request::post("http://example.com/test")
82 .header(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())
83 .body(Body::from(body))
84 .unwrap();
85
86 assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, body);
87 }
88
89 #[crate::test]
90 async fn test_from_query() {
91 check_query("http://example.com/test", b"").await;
92
93 check_query("http://example.com/test?page=0&size=10", b"page=0&size=10").await;
94 }
95
96 #[crate::test]
97 async fn test_from_head_query() {
98 check_head_query("http://example.com/test", b"").await;
99
100 check_head_query("http://example.com/test?page=0&size=10", b"page=0&size=10").await;
101 }
102
103 #[crate::test]
104 async fn test_from_body() {
105 check_body(b"").await;
106
107 check_body(b"username=user&password=secure%20password").await;
108 }
109
110 #[crate::test]
111 async fn test_incorrect_content_type() {
112 let req = Request::post("http://example.com/test")
113 .body(Body::from("page=0&size=10"))
114 .unwrap();
115
116 assert!(matches!(
117 RawForm::from_request(req, &()).await.unwrap_err(),
118 RawFormRejection::InvalidFormContentType(InvalidFormContentType)
119 ))
120 }
121}