Files
axum/src/extract/mod.rs
T

571 lines
16 KiB
Rust
Raw Normal View History

2021-06-07 16:28:40 +02:00
//! Types and traits for extracting data from requests.
2021-06-08 21:21:20 +02:00
//!
2021-06-09 09:03:09 +02:00
//! A handler function is an async function take takes any number of
//! "extractors" as arguments. An extractor is a type that implements
//! [`FromRequest`](crate::extract::FromRequest).
2021-06-08 21:21:20 +02:00
//!
//! For example, [`Json`] is an extractor that consumes the request body and
//! deserializes it as JSON into some target type:
//!
//! ```rust,no_run
2021-07-09 21:36:14 +02:00
//! use axum::prelude::*;
2021-06-08 21:21:20 +02:00
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct CreateUser {
//! email: String,
//! password: String,
//! }
//!
2021-06-09 09:03:09 +02:00
//! async fn create_user(payload: extract::Json<CreateUser>) {
2021-06-08 21:21:20 +02:00
//! let payload: CreateUser = payload.0;
//!
//! // ...
//! }
//!
//! let app = route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
//!
//! # Defining custom extractors
//!
//! You can also define your own extractors by implementing [`FromRequest`]:
//!
//! ```rust,no_run
2021-07-22 13:23:50 +02:00
//! use axum::{async_trait, extract::{FromRequest, RequestParts}, prelude::*};
2021-06-08 21:21:20 +02:00
//! use http::{StatusCode, header::{HeaderValue, USER_AGENT}};
//!
//! struct ExtractUserAgent(HeaderValue);
//!
//! #[async_trait]
2021-06-19 12:50:33 +02:00
//! impl<B> FromRequest<B> for ExtractUserAgent
//! where
//! B: Send,
//! {
2021-06-08 21:21:20 +02:00
//! type Rejection = (StatusCode, &'static str);
//!
2021-07-22 13:23:50 +02:00
//! async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
//! let user_agent = req.headers().and_then(|headers| headers.get(USER_AGENT));
//!
//! if let Some(user_agent) = user_agent {
2021-06-08 21:21:20 +02:00
//! Ok(ExtractUserAgent(user_agent.clone()))
//! } else {
//! Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
//! }
//! }
//! }
//!
2021-06-09 09:03:09 +02:00
//! async fn handler(user_agent: ExtractUserAgent) {
2021-06-08 21:21:20 +02:00
//! let user_agent: HeaderValue = user_agent.0;
//!
//! // ...
//! }
//!
//! let app = route("/foo", get(handler));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
//!
//! # Multiple extractors
//!
//! Handlers can also contain multiple extractors:
//!
//! ```rust,no_run
2021-07-09 21:36:14 +02:00
//! use axum::prelude::*;
2021-06-08 21:21:20 +02:00
//! use std::collections::HashMap;
//!
//! async fn handler(
//! // Extract captured parameters from the URL
//! params: extract::UrlParamsMap,
//! // Parse query string into a `HashMap`
//! query_params: extract::Query<HashMap<String, String>>,
//! // Buffer the request body into a `Bytes`
//! bytes: bytes::Bytes,
//! ) {
//! // ...
//! }
//!
//! let app = route("/foo", get(handler));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
//!
2021-07-10 23:46:14 +02:00
//! Note that only one extractor can consume the request body. If multiple body extractors are
//! applied a `500 Internal Server Error` response will be returned.
//!
2021-06-08 21:21:20 +02:00
//! # Optional extractors
//!
//! Wrapping extractors in `Option` will make them optional:
//!
//! ```rust,no_run
2021-07-09 21:36:14 +02:00
//! use axum::{extract::Json, prelude::*};
2021-06-08 21:21:20 +02:00
//! use serde_json::Value;
//!
2021-06-09 09:03:09 +02:00
//! async fn create_user(payload: Option<Json<Value>>) {
2021-06-08 21:21:20 +02:00
//! if let Some(payload) = payload {
//! // We got a valid JSON payload
//! } else {
//! // Payload wasn't valid JSON
//! }
//! }
//!
//! let app = route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
//!
2021-06-13 12:06:59 +02:00
//! Wrapping extractors in `Result` makes them optional and gives you the reason
//! the extraction failed:
//!
//! ```rust,no_run
2021-07-09 21:36:14 +02:00
//! use axum::{extract::{Json, rejection::JsonRejection}, prelude::*};
2021-06-13 12:06:59 +02:00
//! use serde_json::Value;
//!
//! async fn create_user(payload: Result<Json<Value>, JsonRejection>) {
//! match payload {
//! Ok(payload) => {
//! // We got a valid JSON payload
//! }
//! Err(JsonRejection::MissingJsonContentType(_)) => {
//! // Request didn't have `Content-Type: application/json`
//! // header
//! }
//! Err(JsonRejection::InvalidJsonBody(_)) => {
//! // Couldn't deserialize the body into the target type
//! }
//! Err(JsonRejection::BodyAlreadyExtracted(_)) => {
//! // Another extractor had already consumed the body
//! }
//! Err(_) => {
//! // `JsonRejection` is marked `#[non_exhaustive]` so match must
//! // include a catch-all case.
//! }
//! }
//! }
//!
//! let app = route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-13 12:06:59 +02:00
//! # };
//! ```
//!
2021-06-08 21:21:20 +02:00
//! # Reducing boilerplate
//!
//! If you're feeling adventorous you can even deconstruct the extractors
//! directly on the function signature:
//!
//! ```rust,no_run
2021-07-09 21:36:14 +02:00
//! use axum::{extract::Json, prelude::*};
2021-06-08 21:21:20 +02:00
//! use serde_json::Value;
//!
2021-06-09 09:03:09 +02:00
//! async fn create_user(Json(value): Json<Value>) {
2021-06-08 21:21:20 +02:00
//! // `value` is of type `Value`
//! }
//!
//! let app = route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
2021-07-23 00:26:08 +02:00
//!
//! # Request body extractors
//!
//! Most of the time your request body type will be [`body::Body`] (a re-export
//! of [`hyper::Body`]), which is directly supported by all extractors.
//!
//! However if you're applying a tower middleware that changes the response you
//! might have to apply a different body type to some extractors:
//!
//! ```rust
//! use std::{
//! task::{Context, Poll},
//! pin::Pin,
//! };
//! use tower_http::map_request_body::MapRequestBodyLayer;
//! use axum::prelude::*;
//!
//! struct MyBody<B>(B);
//!
//! impl<B> http_body::Body for MyBody<B>
//! where
//! B: http_body::Body + Unpin,
//! {
//! type Data = B::Data;
//! type Error = B::Error;
//!
//! fn poll_data(
//! mut self: Pin<&mut Self>,
//! cx: &mut Context<'_>,
//! ) -> Poll<Option<Result<Self::Data, Self::Error>>> {
//! Pin::new(&mut self.0).poll_data(cx)
//! }
//!
//! fn poll_trailers(
//! mut self: Pin<&mut Self>,
//! cx: &mut Context<'_>,
//! ) -> Poll<Result<Option<headers::HeaderMap>, Self::Error>> {
//! Pin::new(&mut self.0).poll_trailers(cx)
//! }
//! }
//!
//! let app =
//! // `String` works directly with any body type
//! route(
//! "/string",
//! get(|_: String| async {})
//! )
//! .route(
//! "/body",
//! // `extract::Body` defaults to `axum::body::Body`
//! // but can be customized
//! get(|_: extract::Body<MyBody<Body>>| async {})
//! )
//! .route(
//! "/body-stream",
//! // same for `extract::BodyStream`
//! get(|_: extract::BodyStream<MyBody<Body>>| async {}),
//! )
//! .route(
//! // and `Request<_>`
//! "/request",
//! get(|_: Request<MyBody<Body>>| async {})
//! )
//! // middleware that changes the request body type
//! .layer(MapRequestBodyLayer::new(MyBody));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-07-23 00:26:08 +02:00
//! # };
//! ```
//!
//! [`body::Body`]: crate::body::Body
2021-06-07 16:28:40 +02:00
2021-08-03 21:55:48 +02:00
use crate::response::IntoResponse;
2021-05-31 12:55:39 +02:00
use async_trait::async_trait;
2021-08-03 21:55:48 +02:00
use http::{header, Extensions, HeaderMap, Method, Request, Uri, Version};
2021-06-13 12:06:59 +02:00
use rejection::*;
2021-08-03 21:55:48 +02:00
use std::convert::Infallible;
2021-05-30 13:24:03 +02:00
pub mod connect_info;
2021-07-09 23:38:59 +02:00
pub mod extractor_middleware;
2021-06-06 11:37:08 +02:00
pub mod rejection;
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
pub mod ws;
2021-08-03 21:55:48 +02:00
mod content_length_limit;
mod extension;
mod form;
2021-08-06 16:17:57 +08:00
mod path;
2021-08-03 21:55:48 +02:00
mod query;
mod raw_query;
mod request_parts;
mod tuple;
mod url_params;
mod url_params_map;
2021-07-09 23:38:59 +02:00
#[doc(inline)]
#[allow(deprecated)]
2021-08-03 21:55:48 +02:00
pub use self::{
connect_info::ConnectInfo,
content_length_limit::ContentLengthLimit,
extension::Extension,
extractor_middleware::extractor_middleware,
form::Form,
2021-08-06 16:17:57 +08:00
path::Path,
2021-08-03 21:55:48 +02:00
query::Query,
raw_query::RawQuery,
request_parts::{Body, BodyStream},
url_params::UrlParams,
url_params_map::UrlParamsMap,
};
#[doc(no_inline)]
pub use crate::Json;
#[cfg(feature = "multipart")]
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
pub mod multipart;
#[cfg(feature = "multipart")]
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
#[doc(inline)]
pub use self::multipart::Multipart;
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
#[doc(inline)]
pub use self::ws::WebSocketUpgrade;
2021-08-03 21:55:48 +02:00
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
mod typed_header;
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
#[doc(inline)]
pub use self::typed_header::TypedHeader;
2021-06-08 21:21:20 +02:00
/// Types that can be created from requests.
///
/// See the [module docs](crate::extract) for more details.
///
/// # What is the `B` type parameter?
///
/// `FromRequest` is generic over the request body (the `B` in
/// [`http::Request<B>`]). This is to allow `FromRequest` to be usable will any
/// type of request body. This is necessary because some middleware change the
/// request body, for example to add timeouts.
///
/// If you're writing your own `FromRequest` that wont be used outside your
/// application, and not using any middleware that changes the request body, you
/// can most likely use `axum::body::Body`. Note this is also the default.
///
/// If you're writing a library, thats intended for others to use, its recommended
/// to keep the generic type parameter:
///
/// ```rust
/// use axum::{
/// async_trait,
/// extract::{FromRequest, RequestParts},
/// };
///
/// struct MyExtractor;
///
/// #[async_trait]
/// impl<B> FromRequest<B> for MyExtractor
/// where
/// B: Send, // required by `async_trait`
/// {
/// type Rejection = http::StatusCode;
///
/// async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
/// // ...
/// # unimplemented!()
/// }
/// }
/// ```
///
/// This ensures your extractor is as flexible as possible.
///
/// [`http::Request<B>`]: http::Request
2021-05-31 12:55:39 +02:00
#[async_trait]
pub trait FromRequest<B = crate::body::Body>: Sized {
2021-06-08 21:21:20 +02:00
/// If the extractor fails it'll use this "rejection" type. A rejection is
/// a kind of error that can be converted into a response.
2021-06-06 22:41:52 +02:00
type Rejection: IntoResponse;
2021-05-31 14:04:05 +02:00
2021-06-08 21:21:20 +02:00
/// Perform the extraction.
2021-07-22 13:23:50 +02:00
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection>;
}
/// The type used with [`FromRequest`] to extract data from requests.
///
/// Has several convenience methods for getting owned parts of the request.
#[derive(Debug)]
pub struct RequestParts<B = crate::body::Body> {
method: Method,
uri: Uri,
version: Version,
2021-07-22 13:23:50 +02:00
headers: Option<HeaderMap>,
extensions: Option<Extensions>,
body: Option<B>,
}
impl<B> RequestParts<B> {
pub(crate) fn new(req: Request<B>) -> Self {
let (
http::request::Parts {
method,
uri,
version,
headers,
extensions,
..
},
body,
) = req.into_parts();
RequestParts {
method,
uri,
version,
2021-07-22 13:23:50 +02:00
headers: Some(headers),
extensions: Some(extensions),
body: Some(body),
}
}
#[allow(clippy::wrong_self_convention)]
pub(crate) fn into_request(&mut self) -> Request<B> {
let Self {
method,
uri,
version,
headers,
extensions,
body,
} = self;
let mut req = Request::new(body.take().expect("body already extracted"));
*req.method_mut() = method.clone();
*req.uri_mut() = uri.clone();
*req.version_mut() = *version;
2021-07-22 13:23:50 +02:00
if let Some(headers) = headers.take() {
*req.headers_mut() = headers;
}
if let Some(extensions) = extensions.take() {
*req.extensions_mut() = extensions;
}
req
}
/// Gets a reference the request method.
pub fn method(&self) -> &Method {
&self.method
2021-07-22 13:23:50 +02:00
}
/// Gets a mutable reference to the request method.
pub fn method_mut(&mut self) -> &mut Method {
&mut self.method
2021-07-22 13:23:50 +02:00
}
/// Gets a reference the request URI.
pub fn uri(&self) -> &Uri {
&self.uri
2021-07-22 13:23:50 +02:00
}
/// Gets a mutable reference to the request URI.
pub fn uri_mut(&mut self) -> &mut Uri {
&mut self.uri
2021-07-22 13:23:50 +02:00
}
/// Get the request HTTP version.
pub fn version(&self) -> Version {
2021-07-22 13:23:50 +02:00
self.version
}
/// Gets a mutable reference to the request HTTP version.
pub fn version_mut(&mut self) -> &mut Version {
&mut self.version
2021-07-22 13:23:50 +02:00
}
/// Gets a reference to the request headers.
///
/// Returns `None` if the headers has been taken by another extractor.
pub fn headers(&self) -> Option<&HeaderMap> {
self.headers.as_ref()
}
/// Gets a mutable reference to the request headers.
///
/// Returns `None` if the headers has been taken by another extractor.
pub fn headers_mut(&mut self) -> Option<&mut HeaderMap> {
self.headers.as_mut()
}
/// Takes the headers out of the request, leaving a `None` in its place.
pub fn take_headers(&mut self) -> Option<HeaderMap> {
self.headers.take()
}
/// Gets a reference to the request extensions.
///
/// Returns `None` if the extensions has been taken by another extractor.
pub fn extensions(&self) -> Option<&Extensions> {
self.extensions.as_ref()
}
/// Gets a mutable reference to the request extensions.
///
/// Returns `None` if the extensions has been taken by another extractor.
pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
self.extensions.as_mut()
}
/// Takes the extensions out of the request, leaving a `None` in its place.
pub fn take_extensions(&mut self) -> Option<Extensions> {
self.extensions.take()
}
/// Gets a reference to the request body.
///
/// Returns `None` if the body has been taken by another extractor.
pub fn body(&self) -> Option<&B> {
self.body.as_ref()
}
/// Gets a mutable reference to the request body.
///
/// Returns `None` if the body has been taken by another extractor.
pub fn body_mut(&mut self) -> Option<&mut B> {
self.body.as_mut()
}
/// Takes the body out of the request, leaving a `None` in its place.
pub fn take_body(&mut self) -> Option<B> {
self.body.take()
}
2021-05-31 14:04:05 +02:00
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-19 12:50:33 +02:00
impl<T, B> FromRequest<B> for Option<T>
2021-05-30 13:24:03 +02:00
where
2021-06-19 12:50:33 +02:00
T: FromRequest<B>,
B: Send,
2021-05-30 13:24:03 +02:00
{
2021-05-31 22:54:21 +02:00
type Rejection = Infallible;
2021-07-22 13:23:50 +02:00
async fn from_request(req: &mut RequestParts<B>) -> Result<Option<T>, Self::Rejection> {
2021-05-31 12:55:39 +02:00
Ok(T::from_request(req).await.ok())
2021-05-30 13:24:03 +02:00
}
}
2021-06-13 12:06:59 +02:00
#[async_trait]
2021-06-19 12:50:33 +02:00
impl<T, B> FromRequest<B> for Result<T, T::Rejection>
2021-06-13 12:06:59 +02:00
where
2021-06-19 12:50:33 +02:00
T: FromRequest<B>,
B: Send,
2021-06-13 12:06:59 +02:00
{
type Rejection = Infallible;
2021-07-22 13:23:50 +02:00
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
2021-06-13 12:06:59 +02:00
Ok(T::from_request(req).await)
}
}
pub(crate) fn has_content_type<B>(
2021-07-22 13:23:50 +02:00
req: &RequestParts<B>,
expected_content_type: &str,
) -> Result<bool, HeadersAlreadyExtracted> {
let content_type = if let Some(content_type) = req
.headers()
.ok_or(HeadersAlreadyExtracted)?
.get(header::CONTENT_TYPE)
{
2021-05-31 12:22:16 +02:00
content_type
} else {
2021-07-22 13:23:50 +02:00
return Ok(false);
2021-05-31 12:22:16 +02:00
};
2021-05-30 13:24:03 +02:00
2021-05-31 12:22:16 +02:00
let content_type = if let Ok(content_type) = content_type.to_str() {
content_type
} else {
2021-07-22 13:23:50 +02:00
return Ok(false);
2021-05-31 12:22:16 +02:00
};
2021-07-22 13:23:50 +02:00
Ok(content_type.starts_with(expected_content_type))
2021-05-30 13:24:03 +02:00
}
pub(crate) fn take_body<B>(req: &mut RequestParts<B>) -> Result<B, BodyAlreadyExtracted> {
2021-07-22 13:23:50 +02:00
req.take_body().ok_or(BodyAlreadyExtracted)
2021-05-31 22:54:21 +02:00
}