//! Types and traits for extracting data from requests.
//!
//! A handler function must always take `Request
` as its first argument
//! but any arguments following are called "extractors". Any type that
//! implements [`FromRequest`](FromRequest) can be used as an extractor.
//!
//! For example, [`Json`] is an extractor that consumes the request body and
//! deserializes it as JSON into some target type:
//!
//! ```rust,no_run
//! use tower_web::prelude::*;
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct CreateUser {
//! email: String,
//! password: String,
//! }
//!
//! async fn create_user(req: Request, payload: extract::Json) {
//! let payload: CreateUser = payload.0;
//!
//! // ...
//! }
//!
//! let app = route("/users", post(create_user));
//! # async {
//! # hyper::Server::bind(&"".parse().unwrap()).serve(tower::make::Shared::new(app)).await;
//! # };
//! ```
//!
//! Technically extractors can also be used as "guards", for example to require
//! that requests are authorized. However the recommended way to do that is
//! using Tower middleware, such as [`tower_http::auth::RequireAuthorization`].
//! Extractors have to be applied to each handler, whereas middleware can be
//! applied to a whole stack at once, which is typically what you want for
//! authorization.
//!
//! # Defining custom extractors
//!
//! You can also define your own extractors by implementing [`FromRequest`]:
//!
//! ```rust,no_run
//! use tower_web::{async_trait, extract::FromRequest, prelude::*};
//! use http::{StatusCode, header::{HeaderValue, USER_AGENT}};
//!
//! struct ExtractUserAgent(HeaderValue);
//!
//! #[async_trait]
//! impl FromRequest for ExtractUserAgent {
//! type Rejection = (StatusCode, &'static str);
//!
//! async fn from_request(req: &mut Request) -> Result {
//! if let Some(user_agent) = req.headers().get(USER_AGENT) {
//! Ok(ExtractUserAgent(user_agent.clone()))
//! } else {
//! Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
//! }
//! }
//! }
//!
//! async fn handler(req: Request, user_agent: ExtractUserAgent) {
//! let user_agent: HeaderValue = user_agent.0;
//!
//! // ...
//! }
//!
//! let app = route("/foo", get(handler));
//! # async {
//! # hyper::Server::bind(&"".parse().unwrap()).serve(tower::make::Shared::new(app)).await;
//! # };
//! ```
//!
//! # Multiple extractors
//!
//! Handlers can also contain multiple extractors:
//!
//! ```rust,no_run
//! use tower_web::prelude::*;
//! use std::collections::HashMap;
//!
//! async fn handler(
//! req: Request,
//! // Extract captured parameters from the URL
//! params: extract::UrlParamsMap,
//! // Parse query string into a `HashMap`
//! query_params: extract::Query>,
//! // Buffer the request body into a `Bytes`
//! bytes: bytes::Bytes,
//! ) {
//! // ...
//! }
//!
//! let app = route("/foo", get(handler));
//! # async {
//! # hyper::Server::bind(&"".parse().unwrap()).serve(tower::make::Shared::new(app)).await;
//! # };
//! ```
//!
//! # Optional extractors
//!
//! Wrapping extractors in `Option` will make them optional:
//!
//! ```rust,no_run
//! use tower_web::{extract::Json, prelude::*};
//! use serde_json::Value;
//!
//! async fn create_user(req: Request, payload: Option>) {
//! 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 {
//! # hyper::Server::bind(&"".parse().unwrap()).serve(tower::make::Shared::new(app)).await;
//! # };
//! ```
//!
//! # Reducing boilerplate
//!
//! If you're feeling adventorous you can even deconstruct the extractors
//! directly on the function signature:
//!
//! ```rust,no_run
//! use tower_web::{extract::Json, prelude::*};
//! use serde_json::Value;
//!
//! async fn create_user(req: Request, Json(value): Json) {
//! // `value` is of type `Value`
//! }
//!
//! let app = route("/users", post(create_user));
//! # async {
//! # hyper::Server::bind(&"".parse().unwrap()).serve(tower::make::Shared::new(app)).await;
//! # };
//! ```
use crate::{body::Body, response::IntoResponse};
use async_trait::async_trait;
use bytes::Bytes;
use http::{header, Request, Response};
use rejection::{
BodyAlreadyTaken, FailedToBufferBody, InvalidJsonBody, InvalidUrlParam, InvalidUtf8,
LengthRequired, MissingExtension, MissingJsonContentType, MissingRouteParams, PayloadTooLarge,
QueryStringMissing, UrlParamsAlreadyTaken,
};
use serde::de::DeserializeOwned;
use std::{collections::HashMap, convert::Infallible, str::FromStr};
pub mod rejection;
/// Types that can be created from requests.
///
/// See the [module docs](crate::extract) for more details.
#[async_trait]
pub trait FromRequest: Sized {
/// If the extractor fails it'll use this "rejection" type. A rejection is
/// a kind of error that can be converted into a response.
type Rejection: IntoResponse;
/// Perform the extraction.
async fn from_request(req: &mut Request) -> Result;
}
#[async_trait]
impl FromRequest for Option
where
T: FromRequest,
{
type Rejection = Infallible;
async fn from_request(req: &mut Request) -> Result