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
//! Method-adaptive params extractor: one handler serves `GET /x?a=1` and
//! `QUERY /x` with body `a=1`.
//!
//! [`Params<T>`] reads `T` from the querystring on GET/HEAD and from the
//! body on QUERY (RFC 10008), so a search or filter endpoint takes either
//! transport with no branching in the handler:
//!
//! ```ignore
//! use rustango::params::Params;
//! use rustango::http_query::QueryRouterExt;
//! use axum::routing::get;
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Search { q: String, page: Option<u32> }
//!
//! async fn search(Params(s): Params<Search>) -> String {
//! format!("q={} page={:?}", s.q, s.page)
//! }
//!
//! // One handler, both transports.
//! let app = axum::Router::new().route("/search", get(search).query(search));
//! ```
//!
//! On QUERY the body is parsed by `Content-Type`:
//! - `application/x-www-form-urlencoded`, or no `Content-Type` → the same
//! `serde_urlencoded` path as the querystring, so `T` deserializes the
//! same way on both transports.
//! - `application/json`, or any `…+json` suffix → `serde_json`.
//! - anything else → `415 Unsupported Media Type`.
//!
//! Any other method gets `405`. Body size is capped upstream by the
//! body-limit layer.
//!
//! ## Arrays and nested criteria
//!
//! The urlencoded path is flat and single-value, like axum's
//! [`Query`](axum::extract::Query) and [`Form`](axum::extract::Form): it
//! cannot express nesting, and a repeated key (`?tag=a&tag=b`) is a
//! `duplicate field` error, not a `Vec`. For arrays or nesting, send a
//! JSON body on QUERY.
//!
//! [`Params<T>`]: crate::params::Params
use axum::body::Bytes;
use axum::extract::{FromRequest, Request};
use axum::http::header::CONTENT_TYPE;
use axum::http::{Method, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::de::DeserializeOwned;
use crate::api_errors::ApiError;
/// Extractor that reads `T` from the querystring on GET/HEAD and from the
/// request body on QUERY. See the [module docs](self).
pub struct Params<T>(pub T);
impl<T, S> FromRequest<S> for Params<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = ParamsRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let method = req.method().clone();
if method == Method::GET || method == Method::HEAD {
let query = req.uri().query().unwrap_or_default();
// Querystring parse failure → 400, matching axum's `Query`.
let value = serde_urlencoded::from_str(query)
.map_err(|e| ParamsRejection::DeserializeQuery(e.to_string()))?;
return Ok(Params(value));
}
if method == *crate::http_query::QUERY {
// Read Content-Type first: `Bytes::from_request` consumes `req`.
let kind = body_kind(&req)?;
let bytes = Bytes::from_request(req, state)
.await
.map_err(|e| ParamsRejection::BodyRead(Box::new(e.into_response())))?;
// Body parse failure → 422, matching axum's `Form`.
let value = match kind {
BodyKind::UrlEncoded => serde_urlencoded::from_bytes(&bytes)
.map_err(|e| ParamsRejection::DeserializeBody(e.to_string()))?,
BodyKind::Json => serde_json::from_slice(&bytes)
.map_err(|e| ParamsRejection::DeserializeBody(e.to_string()))?,
};
return Ok(Params(value));
}
Err(ParamsRejection::MethodNotAllowed)
}
}
/// How a QUERY request body should be parsed, resolved from `Content-Type`.
enum BodyKind {
UrlEncoded,
Json,
}
/// Classify a QUERY body by its `Content-Type`; unsupported types get
/// `415`. A missing header means urlencoded, like an HTML form post. A
/// header that is present but unreadable is a 415, never a silent
/// downgrade to urlencoded.
fn body_kind(req: &Request) -> Result<BodyKind, ParamsRejection> {
let Some(ct) = req.headers().get(CONTENT_TYPE) else {
return Ok(BodyKind::UrlEncoded);
};
let Ok(ct_str) = ct.to_str() else {
return Err(ParamsRejection::UnsupportedMediaType(
"<non-ascii Content-Type>".to_owned(),
));
};
let essence = ct_str
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
match essence.as_str() {
"" | "application/x-www-form-urlencoded" => Ok(BodyKind::UrlEncoded),
"application/json" => Ok(BodyKind::Json),
other if other.ends_with("+json") => Ok(BodyKind::Json),
other => Err(ParamsRejection::UnsupportedMediaType(other.to_owned())),
}
}
/// Why a [`Params`] extraction failed. Renders to a JSON [`ApiError`].
pub enum ParamsRejection {
/// The querystring didn't deserialize into `T` (`400`, matching axum's
/// [`Query`](axum::extract::Query)).
DeserializeQuery(String),
/// The QUERY body didn't deserialize into `T` (`422`, matching axum's
/// [`Form`](axum::extract::Form): the request is well-formed but its
/// content is unprocessable).
DeserializeBody(String),
/// A QUERY body arrived with an unsupported `Content-Type` (`415`).
UnsupportedMediaType(String),
/// The request used a method other than GET / HEAD / QUERY (`405`).
MethodNotAllowed,
/// The body could not be read (size limit, IO). Carries the `Bytes`
/// rejection response as-is. Boxed to keep the enum small.
BodyRead(Box<Response>),
}
// Hand-written because the `BodyRead` payload is an axum `Response`,
// which is not `Debug`.
impl std::fmt::Debug for ParamsRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParamsRejection::DeserializeQuery(m) => {
f.debug_tuple("DeserializeQuery").field(m).finish()
}
ParamsRejection::DeserializeBody(m) => {
f.debug_tuple("DeserializeBody").field(m).finish()
}
ParamsRejection::UnsupportedMediaType(m) => {
f.debug_tuple("UnsupportedMediaType").field(m).finish()
}
ParamsRejection::MethodNotAllowed => f.write_str("MethodNotAllowed"),
ParamsRejection::BodyRead(r) => f.debug_tuple("BodyRead").field(&r.status()).finish(),
}
}
}
impl IntoResponse for ParamsRejection {
fn into_response(self) -> Response {
match self {
ParamsRejection::DeserializeQuery(msg) => {
ApiError::bad_request(format!("could not parse query params: {msg}"))
.into_response()
}
ParamsRejection::DeserializeBody(msg) => {
ApiError::validation(format!("could not parse QUERY body: {msg}")).into_response()
}
ParamsRejection::UnsupportedMediaType(ct) => ApiError::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"unsupported_media_type",
format!(
"QUERY body Content-Type `{ct}` is not supported; \
use application/x-www-form-urlencoded or application/json"
),
)
.into_response(),
ParamsRejection::MethodNotAllowed => {
let mut resp = ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"method_not_allowed",
"the Params extractor accepts GET, HEAD, and QUERY only",
)
.into_response();
// RFC 9110 §15.5.6 — a 405 MUST carry `Allow`.
resp.headers_mut().insert(
axum::http::header::ALLOW,
axum::http::HeaderValue::from_static("GET,HEAD,QUERY"),
);
resp
}
ParamsRejection::BodyRead(resp) => *resp,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http_query::QueryRouterExt;
use axum::body::Body;
use axum::routing::{get, post};
use axum::Router;
use serde::Deserialize;
use tower::ServiceExt;
// Flat struct — the shape the urlencoded/GET transport supports.
#[derive(Deserialize)]
struct Search {
q: String,
page: Option<u32>,
}
async fn show(Params(s): Params<Search>) -> String {
format!("q={};page={:?}", s.q, s.page)
}
// Nested/array struct — only expressible via a JSON body on QUERY.
#[derive(Deserialize)]
struct RichSearch {
q: String,
#[serde(default)]
tags: Vec<String>,
}
async fn show_rich(Params(s): Params<RichSearch>) -> String {
format!("q={};tags={:?}", s.q, s.tags)
}
fn app() -> Router {
Router::new().route("/s", get(show).query(show))
}
async fn send(app: Router, method: &str, uri: &str, ct: Option<&str>, body: &str) -> Response {
let mut b = Request::builder()
.method(Method::from_bytes(method.as_bytes()).unwrap())
.uri(uri);
if let Some(ct) = ct {
b = b.header(CONTENT_TYPE, ct);
}
app.oneshot(b.body(Body::from(body.to_owned())).unwrap())
.await
.unwrap()
}
async fn text(resp: Response) -> (StatusCode, String) {
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
(status, String::from_utf8(bytes.to_vec()).unwrap())
}
#[tokio::test]
async fn get_and_query_urlencoded_are_identical() {
let qs = "q=hi&page=2";
let (gs, gb) = text(send(app(), "GET", &format!("/s?{qs}"), None, "").await).await;
let (qsx, qb) = text(
send(
app(),
"QUERY",
"/s",
Some("application/x-www-form-urlencoded"),
qs,
)
.await,
)
.await;
assert_eq!(gs, StatusCode::OK);
assert_eq!(qsx, StatusCode::OK);
assert_eq!(
gb, qb,
"GET querystring and QUERY body must deserialize the same"
);
assert_eq!(gb, "q=hi;page=Some(2)");
}
#[tokio::test]
async fn query_json_body_supports_arrays() {
let app = Router::new().route("/r", get(show_rich).query(show_rich));
let (s, b) = text(
send(
app,
"QUERY",
"/r",
Some("application/json"),
r#"{"q":"hi","tags":["x","y"]}"#,
)
.await,
)
.await;
assert_eq!(s, StatusCode::OK);
assert_eq!(b, "q=hi;tags=[\"x\", \"y\"]");
}
#[tokio::test]
async fn query_json_suffix_content_type() {
let app = Router::new().route("/r", get(show_rich).query(show_rich));
let (s, _) = text(
send(
app,
"QUERY",
"/r",
Some("application/vnd.api+json"),
r#"{"q":"hi","tags":[]}"#,
)
.await,
)
.await;
assert_eq!(s, StatusCode::OK);
}
#[tokio::test]
async fn query_missing_content_type_is_urlencoded() {
let (s, b) = text(send(app(), "QUERY", "/s", None, "q=hi").await).await;
assert_eq!(s, StatusCode::OK);
assert_eq!(b, "q=hi;page=None");
}
#[tokio::test]
async fn query_unsupported_content_type_is_415() {
let (s, _) = text(send(app(), "QUERY", "/s", Some("text/plain"), "q=hi").await).await;
assert_eq!(s, StatusCode::UNSUPPORTED_MEDIA_TYPE);
}
#[tokio::test]
async fn missing_required_field_in_querystring_is_400() {
let (s, _) = text(send(app(), "GET", "/s?page=1", None, "").await).await;
assert_eq!(s, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn invalid_query_body_is_422() {
// `page` is not a u32: well-formed request, bad content → 422.
let (s, _) = text(
send(
app(),
"QUERY",
"/s",
Some("application/x-www-form-urlencoded"),
"q=hi&page=abc",
)
.await,
)
.await;
assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn method_other_than_get_head_query_is_405_with_allow() {
// Mount on POST so the request reaches the extractor; otherwise
// routing would 405 first.
let app = Router::new().route("/p", post(show));
let resp = send(
app,
"POST",
"/p",
Some("application/x-www-form-urlencoded"),
"q=hi",
)
.await;
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(
resp.headers()
.get(axum::http::header::ALLOW)
.and_then(|v| v.to_str().ok()),
Some("GET,HEAD,QUERY"),
"405 must advertise the allowed methods (RFC 9110)"
);
}
}