Files
axum/src/extract/mod.rs
T

769 lines
21 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-06-13 11:22:02 +02:00
//! use awebframework::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 {
//! # app.serve(&"".parse().unwrap()).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-06-13 11:22:02 +02:00
//! use awebframework::{async_trait, extract::FromRequest, prelude::*};
2021-06-08 21:21:20 +02:00
//! 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<Body>) -> Result<Self, Self::Rejection> {
//! 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"))
//! }
//! }
//! }
//!
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 {
//! # app.serve(&"".parse().unwrap()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
//!
//! # Multiple extractors
//!
//! Handlers can also contain multiple extractors:
//!
//! ```rust,no_run
2021-06-13 11:22:02 +02:00
//! use awebframework::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 {
//! # app.serve(&"".parse().unwrap()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
//!
//! # Optional extractors
//!
//! Wrapping extractors in `Option` will make them optional:
//!
//! ```rust,no_run
2021-06-13 11:22:02 +02:00
//! use awebframework::{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 {
//! # app.serve(&"".parse().unwrap()).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
//! use awebframework::{extract::{Json, rejection::JsonRejection}, prelude::*};
//! 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 {
//! # app.serve(&"".parse().unwrap()).await.unwrap();
//! # };
//! ```
//!
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-06-13 11:22:02 +02:00
//! use awebframework::{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 {
//! # app.serve(&"".parse().unwrap()).await.unwrap();
2021-06-08 21:21:20 +02:00
//! # };
//! ```
2021-06-07 16:28:40 +02:00
2021-06-01 14:52:18 +02:00
use crate::{body::Body, response::IntoResponse};
2021-05-31 12:55:39 +02:00
use async_trait::async_trait;
2021-06-13 11:01:40 +02:00
use bytes::{Buf, Bytes};
2021-06-13 12:06:59 +02:00
use http::{header, HeaderMap, Method, Request, Uri, Version};
use rejection::*;
2021-05-30 13:24:03 +02:00
use serde::de::DeserializeOwned;
2021-06-12 20:18:21 +02:00
use std::{collections::HashMap, convert::Infallible, mem, str::FromStr};
2021-05-30 13:24:03 +02:00
2021-06-06 11:37:08 +02:00
pub mod rejection;
2021-06-08 21:21:20 +02:00
/// Types that can be created from requests.
///
/// See the [module docs](crate::extract) for more details.
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
pub trait FromRequest: 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-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection>;
2021-05-31 14:04:05 +02:00
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl<T> FromRequest for Option<T>
2021-05-30 13:24:03 +02:00
where
2021-06-06 22:41:52 +02:00
T: FromRequest,
2021-05-30 13:24:03 +02:00
{
2021-05-31 22:54:21 +02:00
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> 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]
impl<T> FromRequest for Result<T, T::Rejection>
where
T: FromRequest,
{
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
Ok(T::from_request(req).await)
}
}
2021-06-08 21:21:20 +02:00
/// Extractor that deserializes query strings into some type.
///
/// `T` is expected to implement [`serde::Deserialize`].
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::prelude::*;
2021-06-08 21:21:20 +02:00
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Pagination {
/// page: usize,
/// per_page: usize,
/// }
///
/// // This will parse query strings like `?page=2&per_page=30` into `Pagination`
/// // structs.
2021-06-09 09:03:09 +02:00
/// async fn list_things(pagination: extract::Query<Pagination>) {
2021-06-08 21:21:20 +02:00
/// let pagination: Pagination = pagination.0;
///
/// // ...
/// }
2021-06-13 11:01:40 +02:00
///
2021-06-08 21:21:20 +02:00
/// let app = route("/list_things", get(list_things));
/// ```
///
2021-06-13 11:01:40 +02:00
/// If the query string cannot be parsed it will reject the request with a `400
2021-06-08 21:21:20 +02:00
/// Bad Request` response.
2021-06-06 15:19:54 +02:00
#[derive(Debug, Clone, Copy, Default)]
2021-06-01 14:52:18 +02:00
pub struct Query<T>(pub T);
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl<T> FromRequest for Query<T>
2021-05-30 13:24:03 +02:00
where
2021-05-31 12:55:39 +02:00
T: DeserializeOwned,
2021-05-30 13:24:03 +02:00
{
2021-06-13 12:06:59 +02:00
type Rejection = QueryRejection;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-06-13 12:06:59 +02:00
let query = req.uri().query().ok_or(QueryStringMissing)?;
2021-06-13 11:01:40 +02:00
let value = serde_urlencoded::from_str(query)
2021-06-13 12:06:59 +02:00
.map_err(FailedToDeserializeQueryString::new::<T, _>)?;
2021-05-31 12:55:39 +02:00
Ok(Query(value))
2021-05-30 13:24:03 +02:00
}
}
2021-06-13 11:01:40 +02:00
/// Extractor that deserializes `application/x-www-form-urlencoded` requests
/// into some type.
///
/// `T` is expected to implement [`serde::Deserialize`].
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::prelude::*;
2021-06-13 11:01:40 +02:00
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct SignUp {
/// username: String,
/// password: String,
/// }
///
/// async fn accept_form(form: extract::Form<SignUp>) {
/// let sign_up: SignUp = form.0;
///
/// // ...
/// }
///
/// let app = route("/sign_up", post(accept_form));
/// ```
///
/// Note that `Content-Type: multipart/form-data` requests are not supported.
#[derive(Debug, Clone, Copy, Default)]
pub struct Form<T>(pub T);
#[async_trait]
impl<T> FromRequest for Form<T>
where
T: DeserializeOwned,
{
2021-06-13 12:06:59 +02:00
type Rejection = FormRejection;
2021-06-13 11:01:40 +02:00
#[allow(warnings)]
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
if !has_content_type(&req, "application/x-www-form-urlencoded") {
2021-06-13 12:06:59 +02:00
Err(InvalidFormContentType)?;
2021-06-13 11:01:40 +02:00
}
if req.method() == Method::GET {
2021-06-13 12:06:59 +02:00
let query = req.uri().query().ok_or(QueryStringMissing)?;
2021-06-13 11:01:40 +02:00
let value = serde_urlencoded::from_str(query)
2021-06-13 12:06:59 +02:00
.map_err(FailedToDeserializeQueryString::new::<T, _>)?;
2021-06-13 11:01:40 +02:00
Ok(Form(value))
} else {
2021-06-13 12:06:59 +02:00
let body = take_body(req)?;
2021-06-13 11:01:40 +02:00
let chunks = hyper::body::aggregate(body)
.await
2021-06-13 12:06:59 +02:00
.map_err(FailedToBufferBody::from_err)?;
2021-06-13 11:01:40 +02:00
let value = serde_urlencoded::from_reader(chunks.reader())
2021-06-13 12:06:59 +02:00
.map_err(FailedToDeserializeQueryString::new::<T, _>)?;
2021-06-13 11:01:40 +02:00
Ok(Form(value))
}
}
}
2021-06-08 21:21:20 +02:00
/// Extractor that deserializes request bodies into some type.
///
/// `T` is expected to implement [`serde::Deserialize`].
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::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));
/// ```
///
2021-06-13 11:01:40 +02:00
/// If the query string cannot be parsed it will reject the request with a `400
2021-06-08 21:21:20 +02:00
/// Bad Request` response.
///
/// The request is required to have a `Content-Type: application/json` header.
2021-06-06 15:19:54 +02:00
#[derive(Debug, Clone, Copy, Default)]
2021-06-01 14:52:18 +02:00
pub struct Json<T>(pub T);
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl<T> FromRequest for Json<T>
2021-05-30 13:24:03 +02:00
where
T: DeserializeOwned,
{
2021-06-13 12:06:59 +02:00
type Rejection = JsonRejection;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-06-08 21:21:20 +02:00
use bytes::Buf;
2021-06-06 11:37:08 +02:00
if has_content_type(req, "application/json") {
2021-06-13 12:06:59 +02:00
let body = take_body(req)?;
2021-05-31 12:22:16 +02:00
2021-06-08 21:21:20 +02:00
let buf = hyper::body::aggregate(body)
2021-05-31 12:55:39 +02:00
.await
2021-06-13 12:06:59 +02:00
.map_err(InvalidJsonBody::from_err)?;
2021-05-31 22:54:21 +02:00
2021-06-13 12:06:59 +02:00
let value = serde_json::from_reader(buf.reader()).map_err(InvalidJsonBody::from_err)?;
2021-05-31 22:54:21 +02:00
2021-05-31 12:55:39 +02:00
Ok(Json(value))
2021-05-31 12:22:16 +02:00
} else {
2021-06-13 12:06:59 +02:00
Err(MissingJsonContentType.into())
2021-05-31 12:22:16 +02:00
}
}
}
2021-05-30 13:24:03 +02:00
2021-05-31 12:22:16 +02:00
fn has_content_type<B>(req: &Request<B>, expected_content_type: &str) -> bool {
let content_type = if let Some(content_type) = req.headers().get(header::CONTENT_TYPE) {
content_type
} else {
return false;
};
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 {
return false;
};
content_type.starts_with(expected_content_type)
2021-05-30 13:24:03 +02:00
}
2021-06-08 21:21:20 +02:00
/// Extractor that gets a value from request extensions.
///
/// This is commonly used to share state across handlers.
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::{AddExtensionLayer, prelude::*};
2021-06-08 21:21:20 +02:00
/// use std::sync::Arc;
///
/// // Some shared state used throughout our application
/// struct State {
/// // ...
/// }
///
2021-06-09 09:03:09 +02:00
/// async fn handler(state: extract::Extension<Arc<State>>) {
2021-06-08 21:21:20 +02:00
/// // ...
/// }
///
/// let state = Arc::new(State { /* ... */ });
///
/// let app = route("/", get(handler))
/// // Add middleware that inserts the state into all incoming request's
/// // extensions.
/// .layer(AddExtensionLayer::new(state));
/// ```
///
/// If the extension is missing it will reject the request with a `500 Interal
/// Server Error` response.
2021-05-30 13:24:03 +02:00
#[derive(Debug, Clone, Copy)]
2021-06-01 14:52:18 +02:00
pub struct Extension<T>(pub T);
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl<T> FromRequest for Extension<T>
2021-05-30 13:24:03 +02:00
where
T: Clone + Send + Sync + 'static,
{
2021-05-31 22:54:21 +02:00
type Rejection = MissingExtension;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-31 12:55:39 +02:00
let value = req
.extensions()
.get::<T>()
.ok_or(MissingExtension)
2021-05-31 12:55:39 +02:00
.map(|x| x.clone())?;
Ok(Extension(value))
2021-05-30 13:24:03 +02:00
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl FromRequest for Bytes {
2021-06-13 12:06:59 +02:00
type Rejection = BytesRejection;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-06-13 12:06:59 +02:00
let body = take_body(req)?;
2021-05-30 14:33:20 +02:00
2021-05-31 12:55:39 +02:00
let bytes = hyper::body::to_bytes(body)
.await
2021-06-13 12:06:59 +02:00
.map_err(FailedToBufferBody::from_err)?;
2021-05-31 12:55:39 +02:00
Ok(bytes)
2021-05-30 14:33:20 +02:00
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl FromRequest for String {
2021-06-13 12:06:59 +02:00
type Rejection = StringRejection;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-06-13 12:06:59 +02:00
let body = take_body(req)?;
2021-05-31 12:22:16 +02:00
2021-05-31 12:55:39 +02:00
let bytes = hyper::body::to_bytes(body)
.await
2021-06-13 12:06:59 +02:00
.map_err(FailedToBufferBody::from_err)?
2021-05-31 12:55:39 +02:00
.to_vec();
2021-06-13 12:06:59 +02:00
let string = String::from_utf8(bytes).map_err(InvalidUtf8::from_err)?;
2021-05-31 12:55:39 +02:00
Ok(string)
2021-05-31 12:22:16 +02:00
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl FromRequest for Body {
2021-06-09 09:03:09 +02:00
type Rejection = BodyAlreadyExtracted;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
take_body(req)
2021-05-31 12:22:16 +02:00
}
}
2021-06-09 09:03:09 +02:00
#[async_trait]
impl FromRequest for Request<Body> {
type Rejection = RequestAlreadyExtracted;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
struct RequestAlreadyExtractedExt;
if req
.extensions_mut()
.insert(RequestAlreadyExtractedExt)
.is_some()
{
Err(RequestAlreadyExtracted)
} else {
Ok(mem::take(req))
}
}
}
#[async_trait]
impl FromRequest for Method {
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
Ok(req.method().clone())
}
}
#[async_trait]
impl FromRequest for Uri {
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
Ok(req.uri().clone())
}
}
#[async_trait]
impl FromRequest for Version {
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
Ok(req.version())
}
}
#[async_trait]
impl FromRequest for HeaderMap {
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
Ok(mem::take(req.headers_mut()))
}
}
2021-06-09 08:14:20 +02:00
/// Extractor that will reject requests with a body larger than some size.
2021-06-08 21:21:20 +02:00
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::prelude::*;
2021-06-08 21:21:20 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn handler(body: extract::ContentLengthLimit<String, 1024>) {
2021-06-08 21:21:20 +02:00
/// // ...
/// }
///
/// let app = route("/", post(handler));
/// ```
///
/// This requires the request to have a `Content-Length` header.
2021-05-30 13:24:03 +02:00
#[derive(Debug, Clone)]
2021-06-09 08:14:20 +02:00
pub struct ContentLengthLimit<T, const N: u64>(pub T);
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-09 08:14:20 +02:00
impl<T, const N: u64> FromRequest for ContentLengthLimit<T, N>
where
T: FromRequest,
{
2021-06-13 12:06:59 +02:00
type Rejection = ContentLengthLimitRejection<T::Rejection>;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-30 14:33:20 +02:00
let content_length = req.headers().get(http::header::CONTENT_LENGTH).cloned();
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
let content_length =
content_length.and_then(|value| value.to_str().ok()?.parse::<u64>().ok());
2021-05-30 14:33:20 +02:00
2021-05-31 12:55:39 +02:00
if let Some(length) = content_length {
if length > N {
2021-06-13 12:06:59 +02:00
return Err(ContentLengthLimitRejection::PayloadTooLarge(
PayloadTooLarge,
));
2021-05-31 12:55:39 +02:00
}
} else {
2021-06-13 12:06:59 +02:00
return Err(ContentLengthLimitRejection::LengthRequired(LengthRequired));
2021-05-31 12:55:39 +02:00
};
2021-05-30 14:33:20 +02:00
2021-06-09 08:14:20 +02:00
let value = T::from_request(req)
2021-05-31 12:55:39 +02:00
.await
2021-06-13 12:06:59 +02:00
.map_err(ContentLengthLimitRejection::Inner)?;
2021-05-30 14:33:20 +02:00
2021-06-09 08:14:20 +02:00
Ok(Self(value))
2021-05-30 13:24:03 +02:00
}
}
2021-05-30 15:44:26 +02:00
2021-06-08 21:21:20 +02:00
/// Extractor that will get captures from the URL.
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::prelude::*;
2021-06-08 21:21:20 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn users_show(params: extract::UrlParamsMap) {
2021-06-08 21:21:20 +02:00
/// let id: Option<&str> = params.get("id");
///
/// // ...
/// }
///
/// let app = route("/users/:id", get(users_show));
/// ```
///
/// Note that you can only have one URL params extractor per handler. If you
/// have multiple it'll response with `500 Internal Server Error`.
2021-06-03 21:36:39 +02:00
#[derive(Debug)]
2021-05-30 16:37:27 +02:00
pub struct UrlParamsMap(HashMap<String, String>);
2021-05-30 15:44:26 +02:00
2021-05-30 16:37:27 +02:00
impl UrlParamsMap {
2021-06-08 21:21:20 +02:00
/// Look up the value for a key.
2021-06-01 00:34:09 +02:00
pub fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).map(|s| &**s)
2021-05-30 15:44:26 +02:00
}
2021-05-30 16:37:27 +02:00
2021-06-08 21:21:20 +02:00
/// Look up the value for a key and parse it into a value of type `T`.
pub fn get_typed<T>(&self, key: &str) -> Option<Result<T, T::Err>>
2021-05-30 16:37:27 +02:00
where
2021-05-30 16:53:27 +02:00
T: FromStr,
2021-05-30 16:37:27 +02:00
{
2021-06-08 21:21:20 +02:00
self.get(key).map(str::parse)
2021-05-30 16:37:27 +02:00
}
2021-05-30 15:44:26 +02:00
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl FromRequest for UrlParamsMap {
2021-06-13 12:06:59 +02:00
type Rejection = UrlParamsMapRejection;
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-30 15:44:26 +02:00
if let Some(params) = req
.extensions_mut()
.get_mut::<Option<crate::routing::UrlParams>>()
{
2021-06-08 21:21:20 +02:00
if let Some(params) = params.take() {
Ok(Self(params.0.into_iter().collect()))
} else {
2021-06-13 12:06:59 +02:00
Err(UrlParamsAlreadyExtracted.into())
2021-06-08 21:21:20 +02:00
}
2021-05-30 15:44:26 +02:00
} else {
2021-06-13 12:06:59 +02:00
Err(MissingRouteParams.into())
2021-05-30 15:44:26 +02:00
}
}
}
2021-05-30 16:53:27 +02:00
2021-06-08 21:21:20 +02:00
/// Extractor that will get captures from the URL and parse them.
///
/// # Example
///
/// ```rust,no_run
2021-06-13 11:22:02 +02:00
/// use awebframework::{extract::UrlParams, prelude::*};
2021-06-08 21:21:20 +02:00
/// use uuid::Uuid;
///
/// async fn users_teams_show(
/// UrlParams(params): UrlParams<(Uuid, Uuid)>,
/// ) {
/// let user_id: Uuid = params.0;
/// let team_id: Uuid = params.1;
///
/// // ...
/// }
///
/// let app = route("/users/:user_id/team/:team_id", get(users_teams_show));
/// ```
///
/// Note that you can only have one URL params extractor per handler. If you
/// have multiple it'll response with `500 Internal Server Error`.
#[derive(Debug)]
2021-06-01 14:52:18 +02:00
pub struct UrlParams<T>(pub T);
2021-05-31 22:54:21 +02:00
2021-05-30 16:53:27 +02:00
macro_rules! impl_parse_url {
() => {};
( $head:ident, $($tail:ident),* $(,)? ) => {
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-06-06 22:41:52 +02:00
impl<$head, $($tail,)*> FromRequest for UrlParams<($head, $($tail,)*)>
2021-05-30 16:53:27 +02:00
where
$head: FromStr + Send,
$( $tail: FromStr + Send, )*
{
2021-06-13 12:06:59 +02:00
type Rejection = UrlParamsRejection;
2021-05-31 22:54:21 +02:00
2021-05-30 16:53:27 +02:00
#[allow(non_snake_case)]
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-30 16:53:27 +02:00
let params = if let Some(params) = req
.extensions_mut()
.get_mut::<Option<crate::routing::UrlParams>>()
{
2021-06-08 21:21:20 +02:00
if let Some(params) = params.take() {
params.0
} else {
2021-06-13 12:06:59 +02:00
return Err(UrlParamsAlreadyExtracted.into());
2021-06-08 21:21:20 +02:00
}
2021-05-30 16:53:27 +02:00
} else {
2021-06-13 12:06:59 +02:00
return Err(MissingRouteParams.into())
2021-05-30 16:53:27 +02:00
};
if let [(_, $head), $((_, $tail),)*] = &*params {
let $head = if let Ok(x) = $head.parse::<$head>() {
x
} else {
2021-06-13 12:06:59 +02:00
return Err(InvalidUrlParam::new::<$head>().into());
2021-05-30 16:53:27 +02:00
};
$(
let $tail = if let Ok(x) = $tail.parse::<$tail>() {
x
} else {
2021-06-13 12:06:59 +02:00
return Err(InvalidUrlParam::new::<$tail>().into());
2021-05-30 16:53:27 +02:00
};
)*
2021-05-31 12:55:39 +02:00
Ok(UrlParams(($head, $($tail,)*)))
2021-05-30 16:53:27 +02:00
} else {
2021-06-13 12:06:59 +02:00
Err(MissingRouteParams.into())
2021-05-30 16:53:27 +02:00
}
}
}
impl_parse_url!($($tail,)*);
};
}
2021-06-07 16:28:40 +02:00
impl_parse_url!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
2021-05-31 22:54:21 +02:00
2021-06-09 09:03:09 +02:00
fn take_body(req: &mut Request<Body>) -> Result<Body, BodyAlreadyExtracted> {
struct BodyAlreadyExtractedExt;
2021-05-31 22:54:21 +02:00
2021-06-09 09:03:09 +02:00
if req
.extensions_mut()
.insert(BodyAlreadyExtractedExt)
.is_some()
{
Err(BodyAlreadyExtracted)
2021-05-31 22:54:21 +02:00
} else {
2021-06-09 09:03:09 +02:00
Ok(mem::take(req.body_mut()))
2021-05-31 22:54:21 +02:00
}
}
2021-06-07 16:28:40 +02:00
macro_rules! impl_from_request_tuple {
() => {};
( $head:ident, $($tail:ident),* $(,)? ) => {
#[allow(non_snake_case)]
#[async_trait]
impl<R, $head, $($tail,)*> FromRequest for ($head, $($tail,)*)
where
R: IntoResponse,
$head: FromRequest<Rejection = R> + Send,
$( $tail: FromRequest<Rejection = R> + Send, )*
{
type Rejection = R;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
let $head = FromRequest::from_request(req).await?;
$( let $tail = FromRequest::from_request(req).await?; )*
Ok(($head, $($tail,)*))
}
}
impl_from_request_tuple!($($tail,)*);
};
}
impl_from_request_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);