2021-01-09 14:17:19 +01:00
|
|
|
//! For path segment extractor documentation, see [`Path`].
|
|
|
|
|
|
|
|
use std::{fmt, ops, sync::Arc};
|
2019-03-10 18:53:56 +01:00
|
|
|
|
|
|
|
use actix_http::error::{Error, ErrorNotFound};
|
|
|
|
use actix_router::PathDeserializer;
|
2020-05-18 04:47:20 +02:00
|
|
|
use futures_util::future::{ready, Ready};
|
2019-03-10 18:53:56 +01:00
|
|
|
use serde::de;
|
|
|
|
|
2021-01-09 14:17:19 +01:00
|
|
|
use crate::{dev::Payload, error::PathError, FromRequest, HttpRequest};
|
2019-03-10 18:53:56 +01:00
|
|
|
|
2021-01-09 14:17:19 +01:00
|
|
|
/// Extract typed data from request path segments.
|
2019-12-20 12:49:05 +01:00
|
|
|
///
|
2021-01-09 14:17:19 +01:00
|
|
|
/// Use [`PathConfig`] to configure extraction process.
|
2019-03-10 18:53:56 +01:00
|
|
|
///
|
2021-02-10 13:10:03 +01:00
|
|
|
/// # Examples
|
2021-01-09 14:17:19 +01:00
|
|
|
/// ```
|
|
|
|
/// use actix_web::{get, web};
|
|
|
|
///
|
|
|
|
/// // extract path info from "/{name}/{count}/index.html" into tuple
|
|
|
|
/// // {name} - deserialize a String
|
|
|
|
/// // {count} - deserialize a u32
|
|
|
|
/// #[get("/")]
|
|
|
|
/// async fn index(path: web::Path<(String, u32)>) -> String {
|
|
|
|
/// let (name, count) = path.into_inner();
|
|
|
|
/// format!("Welcome {}! {}", name, count)
|
2019-03-10 18:53:56 +01:00
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
2021-01-09 14:17:19 +01:00
|
|
|
/// Path segments also can be deserialized into any type that implements [`serde::Deserialize`].
|
|
|
|
/// Path segment labels will be matched with struct field names.
|
2019-03-10 18:53:56 +01:00
|
|
|
///
|
2021-01-09 14:17:19 +01:00
|
|
|
/// ```
|
|
|
|
/// use actix_web::{get, web};
|
|
|
|
/// use serde::Deserialize;
|
2019-03-10 18:53:56 +01:00
|
|
|
///
|
|
|
|
/// #[derive(Deserialize)]
|
|
|
|
/// struct Info {
|
2021-01-09 14:17:19 +01:00
|
|
|
/// name: String,
|
2019-03-10 18:53:56 +01:00
|
|
|
/// }
|
|
|
|
///
|
2021-01-09 14:17:19 +01:00
|
|
|
/// // extract `Info` from a path using serde
|
|
|
|
/// #[get("/")]
|
|
|
|
/// async fn index(info: web::Path<Info>) -> String {
|
|
|
|
/// format!("Welcome {}!", info.name)
|
2019-03-10 18:53:56 +01:00
|
|
|
/// }
|
|
|
|
/// ```
|
2021-01-09 14:17:19 +01:00
|
|
|
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
|
|
|
pub struct Path<T>(T);
|
2019-03-10 18:53:56 +01:00
|
|
|
|
|
|
|
impl<T> Path<T> {
|
2021-01-09 14:17:19 +01:00
|
|
|
/// Unwrap into inner `T` value.
|
2019-03-10 18:53:56 +01:00
|
|
|
pub fn into_inner(self) -> T {
|
2020-07-21 01:54:26 +02:00
|
|
|
self.0
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> AsRef<T> for Path<T> {
|
|
|
|
fn as_ref(&self) -> &T {
|
2020-07-21 01:54:26 +02:00
|
|
|
&self.0
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ops::Deref for Path<T> {
|
|
|
|
type Target = T;
|
|
|
|
|
|
|
|
fn deref(&self) -> &T {
|
2020-07-21 01:54:26 +02:00
|
|
|
&self.0
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ops::DerefMut for Path<T> {
|
|
|
|
fn deref_mut(&mut self) -> &mut T {
|
2020-07-21 01:54:26 +02:00
|
|
|
&mut self.0
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> From<T> for Path<T> {
|
|
|
|
fn from(inner: T) -> Path<T> {
|
2020-07-21 01:54:26 +02:00
|
|
|
Path(inner)
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: fmt::Debug> fmt::Debug for Path<T> {
|
2019-12-07 19:46:51 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2020-07-21 01:54:26 +02:00
|
|
|
self.0.fmt(f)
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: fmt::Display> fmt::Display for Path<T> {
|
2019-12-07 19:46:51 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2020-07-21 01:54:26 +02:00
|
|
|
self.0.fmt(f)
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-09 14:17:19 +01:00
|
|
|
/// See [here](#usage) for example of usage as an extractor.
|
2019-04-13 23:50:54 +02:00
|
|
|
impl<T> FromRequest for Path<T>
|
2019-03-10 18:53:56 +01:00
|
|
|
where
|
|
|
|
T: de::DeserializeOwned,
|
|
|
|
{
|
|
|
|
type Error = Error;
|
2019-11-20 18:33:22 +01:00
|
|
|
type Future = Ready<Result<Self, Error>>;
|
2019-06-12 12:49:56 +02:00
|
|
|
type Config = PathConfig;
|
2019-03-10 18:53:56 +01:00
|
|
|
|
|
|
|
#[inline]
|
2019-04-13 23:50:54 +02:00
|
|
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
2019-06-12 12:49:56 +02:00
|
|
|
let error_handler = req
|
|
|
|
.app_data::<Self::Config>()
|
|
|
|
.map(|c| c.ehandler.clone())
|
|
|
|
.unwrap_or(None);
|
|
|
|
|
2019-11-20 18:33:22 +01:00
|
|
|
ready(
|
|
|
|
de::Deserialize::deserialize(PathDeserializer::new(req.match_info()))
|
2020-07-21 01:54:26 +02:00
|
|
|
.map(Path)
|
2019-11-20 18:33:22 +01:00
|
|
|
.map_err(move |e| {
|
|
|
|
log::debug!(
|
|
|
|
"Failed during Path extractor deserialization. \
|
|
|
|
Request path: {:?}",
|
|
|
|
req.path()
|
|
|
|
);
|
|
|
|
if let Some(error_handler) = error_handler {
|
|
|
|
let e = PathError::Deserialize(e);
|
|
|
|
(error_handler)(e, req)
|
|
|
|
} else {
|
|
|
|
ErrorNotFound(e)
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
)
|
2019-06-12 12:49:56 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Path extractor configuration
|
|
|
|
///
|
2021-01-09 14:17:19 +01:00
|
|
|
/// ```
|
2019-06-12 13:02:45 +02:00
|
|
|
/// use actix_web::web::PathConfig;
|
|
|
|
/// use actix_web::{error, web, App, FromRequest, HttpResponse};
|
2021-01-09 14:17:19 +01:00
|
|
|
/// use serde::Deserialize;
|
2019-06-12 13:02:45 +02:00
|
|
|
///
|
|
|
|
/// #[derive(Deserialize, Debug)]
|
|
|
|
/// enum Folder {
|
|
|
|
/// #[serde(rename = "inbox")]
|
|
|
|
/// Inbox,
|
|
|
|
/// #[serde(rename = "outbox")]
|
|
|
|
/// Outbox,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// // deserialize `Info` from request's path
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index(folder: web::Path<Folder>) -> String {
|
2019-06-12 16:12:15 +02:00
|
|
|
/// format!("Selected folder: {:?}!", folder)
|
2019-06-12 13:02:45 +02:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new().service(
|
|
|
|
/// web::resource("/messages/{folder}")
|
2019-12-20 12:13:09 +01:00
|
|
|
/// .app_data(PathConfig::default().error_handler(|err, req| {
|
2019-06-12 13:02:45 +02:00
|
|
|
/// error::InternalError::from_response(
|
|
|
|
/// err,
|
|
|
|
/// HttpResponse::Conflict().finish(),
|
|
|
|
/// )
|
|
|
|
/// .into()
|
|
|
|
/// }))
|
|
|
|
/// .route(web::post().to(index)),
|
|
|
|
/// );
|
|
|
|
/// }
|
2019-06-12 12:49:56 +02:00
|
|
|
/// ```
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct PathConfig {
|
2019-07-17 11:48:37 +02:00
|
|
|
ehandler: Option<Arc<dyn Fn(PathError, &HttpRequest) -> Error + Send + Sync>>,
|
2019-06-12 12:49:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl PathConfig {
|
|
|
|
/// Set custom error handler
|
|
|
|
pub fn error_handler<F>(mut self, f: F) -> Self
|
|
|
|
where
|
2019-06-12 13:02:45 +02:00
|
|
|
F: Fn(PathError, &HttpRequest) -> Error + Send + Sync + 'static,
|
2019-06-12 12:49:56 +02:00
|
|
|
{
|
|
|
|
self.ehandler = Some(Arc::new(f));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for PathConfig {
|
|
|
|
fn default() -> Self {
|
|
|
|
PathConfig { ehandler: None }
|
2019-03-10 18:53:56 +01:00
|
|
|
}
|
|
|
|
}
|
2019-03-10 19:04:50 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use actix_router::ResourceDef;
|
2019-04-18 20:01:04 +02:00
|
|
|
use derive_more::Display;
|
2021-01-09 14:17:19 +01:00
|
|
|
use serde::Deserialize;
|
2019-03-10 19:04:50 +01:00
|
|
|
|
|
|
|
use super::*;
|
2019-11-26 06:25:50 +01:00
|
|
|
use crate::test::TestRequest;
|
2019-06-12 13:02:45 +02:00
|
|
|
use crate::{error, http, HttpResponse};
|
2019-03-10 19:04:50 +01:00
|
|
|
|
2019-04-18 20:01:04 +02:00
|
|
|
#[derive(Deserialize, Debug, Display)]
|
|
|
|
#[display(fmt = "MyStruct({}, {})", key, value)]
|
|
|
|
struct MyStruct {
|
|
|
|
key: String,
|
|
|
|
value: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Test2 {
|
|
|
|
key: String,
|
|
|
|
value: u32,
|
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_extract_path_single() {
|
|
|
|
let resource = ResourceDef::new("/{value}/");
|
2019-03-10 19:04:50 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let mut req = TestRequest::with_uri("/32/").to_srv_request();
|
|
|
|
resource.match_path(req.match_info_mut());
|
2019-03-10 19:04:50 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let (req, mut pl) = req.into_parts();
|
|
|
|
assert_eq!(*Path::<i8>::from_request(&req, &mut pl).await.unwrap(), 32);
|
|
|
|
assert!(Path::<MyStruct>::from_request(&req, &mut pl).await.is_err());
|
2019-03-10 19:04:50 +01:00
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_tuple_extract() {
|
|
|
|
let resource = ResourceDef::new("/{key}/{value}/");
|
2019-03-10 19:04:50 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
|
|
|
|
resource.match_path(req.match_info_mut());
|
2019-03-10 19:04:50 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let (req, mut pl) = req.into_parts();
|
2020-07-21 01:54:26 +02:00
|
|
|
let (Path(res),) = <(Path<(String, String)>,)>::from_request(&req, &mut pl)
|
2019-11-20 18:33:22 +01:00
|
|
|
.await
|
|
|
|
.unwrap();
|
2020-07-21 01:54:26 +02:00
|
|
|
assert_eq!(res.0, "name");
|
|
|
|
assert_eq!(res.1, "user1");
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2020-07-21 01:54:26 +02:00
|
|
|
let (Path(a), Path(b)) =
|
|
|
|
<(Path<(String, String)>, Path<(String, String)>)>::from_request(
|
|
|
|
&req, &mut pl,
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(a.0, "name");
|
|
|
|
assert_eq!(a.1, "user1");
|
|
|
|
assert_eq!(b.0, "name");
|
|
|
|
assert_eq!(b.1, "user1");
|
2019-11-26 06:25:50 +01:00
|
|
|
|
|
|
|
let () = <()>::from_request(&req, &mut pl).await.unwrap();
|
2019-03-10 19:04:50 +01:00
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_request_extract() {
|
|
|
|
let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
|
|
|
|
|
|
|
|
let resource = ResourceDef::new("/{key}/{value}/");
|
|
|
|
resource.match_path(req.match_info_mut());
|
|
|
|
|
|
|
|
let (req, mut pl) = req.into_parts();
|
|
|
|
let mut s = Path::<MyStruct>::from_request(&req, &mut pl).await.unwrap();
|
|
|
|
assert_eq!(s.key, "name");
|
|
|
|
assert_eq!(s.value, "user1");
|
|
|
|
s.value = "user2".to_string();
|
|
|
|
assert_eq!(s.value, "user2");
|
|
|
|
assert_eq!(
|
|
|
|
format!("{}, {:?}", s, s),
|
|
|
|
"MyStruct(name, user2), MyStruct { key: \"name\", value: \"user2\" }"
|
|
|
|
);
|
|
|
|
let s = s.into_inner();
|
|
|
|
assert_eq!(s.value, "user2");
|
|
|
|
|
2020-07-21 01:54:26 +02:00
|
|
|
let Path(s) = Path::<(String, String)>::from_request(&req, &mut pl)
|
2019-11-26 06:25:50 +01:00
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(s.0, "name");
|
|
|
|
assert_eq!(s.1, "user1");
|
|
|
|
|
|
|
|
let mut req = TestRequest::with_uri("/name/32/").to_srv_request();
|
|
|
|
let resource = ResourceDef::new("/{key}/{value}/");
|
|
|
|
resource.match_path(req.match_info_mut());
|
|
|
|
|
|
|
|
let (req, mut pl) = req.into_parts();
|
|
|
|
let s = Path::<Test2>::from_request(&req, &mut pl).await.unwrap();
|
|
|
|
assert_eq!(s.as_ref().key, "name");
|
|
|
|
assert_eq!(s.value, 32);
|
|
|
|
|
2020-07-21 01:54:26 +02:00
|
|
|
let Path(s) = Path::<(String, u8)>::from_request(&req, &mut pl)
|
2019-11-26 06:25:50 +01:00
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(s.0, "name");
|
|
|
|
assert_eq!(s.1, 32);
|
|
|
|
|
|
|
|
let res = Path::<Vec<String>>::from_request(&req, &mut pl)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(res[0], "name".to_owned());
|
|
|
|
assert_eq!(res[1], "32".to_owned());
|
2019-04-18 20:01:04 +02:00
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_custom_err_handler() {
|
|
|
|
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
|
2019-12-20 12:13:09 +01:00
|
|
|
.app_data(PathConfig::default().error_handler(|err, _| {
|
2019-11-26 06:25:50 +01:00
|
|
|
error::InternalError::from_response(
|
|
|
|
err,
|
|
|
|
HttpResponse::Conflict().finish(),
|
|
|
|
)
|
|
|
|
.into()
|
|
|
|
}))
|
|
|
|
.to_http_parts();
|
|
|
|
|
|
|
|
let s = Path::<(usize,)>::from_request(&req, &mut pl)
|
|
|
|
.await
|
|
|
|
.unwrap_err();
|
|
|
|
let res: HttpResponse = s.into();
|
|
|
|
|
|
|
|
assert_eq!(res.status(), http::StatusCode::CONFLICT);
|
2019-06-12 13:02:45 +02:00
|
|
|
}
|
2019-03-10 19:04:50 +01:00
|
|
|
}
|