actix_web_lab/
path.rs

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
//! For path segment extractor documentation, see [`Path`].

use actix_router::PathDeserializer;
use actix_utils::future::{ready, Ready};
use actix_web::{
    dev::Payload,
    error::{Error, ErrorNotFound},
    FromRequest, HttpRequest,
};
use derive_more::{AsRef, Display, From};
use serde::de;
use tracing::debug;

/// Extract typed data from request path segments.
///
/// Alternative to `web::Path` extractor from Actix Web that allows deconstruction, but omits the
/// implementation of `Deref`.
///
/// Unlike, [`HttpRequest::match_info`], this extractor will fully percent-decode dynamic segments,
/// including `/`, `%`, and `+`.
///
/// # Examples
/// ```
/// use actix_web::get;
/// use actix_web_lab::extract::Path;
///
/// // extract path info from "/{name}/{count}/index.html" into tuple
/// // {name}  - deserialize a String
/// // {count} - deserialize a u32
/// #[get("/{name}/{count}/index.html")]
/// async fn index(Path((name, count)): Path<(String, u32)>) -> String {
///     format!("Welcome {}! {}", name, count)
/// }
/// ```
///
/// Path segments also can be deserialized into any type that implements [`serde::Deserialize`].
/// Path segment labels will be matched with struct field names.
///
/// ```
/// use actix_web::get;
/// use actix_web_lab::extract::Path;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Info {
///     name: String,
/// }
///
/// // extract `Info` from a path using serde
/// #[get("/{name}")]
/// async fn index(info: Path<Info>) -> String {
///     let info = info.into_inner();
///     format!("Welcome {}!", info.name)
/// }
/// ```
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, AsRef, Display, From)]
pub struct Path<T>(pub T);

impl<T> Path<T> {
    /// Unwrap into inner `T` value.
    pub fn into_inner(self) -> T {
        self.0
    }
}

/// See [here](#Examples) for example of usage as an extractor.
impl<T> FromRequest for Path<T>
where
    T: de::DeserializeOwned,
{
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    #[inline]
    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        ready(
            de::Deserialize::deserialize(PathDeserializer::new(req.match_info()))
                .map(Path)
                .map_err(move |err| {
                    debug!(
                        "Failed during Path extractor deserialization. \
                         Request path: {:?}",
                        req.path()
                    );

                    ErrorNotFound(err)
                }),
        )
    }
}

#[cfg(test)]
mod tests {
    use actix_web::{dev::ResourceDef, test::TestRequest};
    use derive_more::Display;
    use serde::Deserialize;

    use super::*;

    #[derive(Deserialize, Debug, Display)]
    #[display(fmt = "MyStruct({key}, {value})")]
    struct MyStruct {
        key: String,
        value: String,
    }

    #[derive(Deserialize)]
    struct Test2 {
        key: String,
        value: u32,
    }

    #[actix_web::test]
    async fn test_extract_path_single() {
        let resource = ResourceDef::new("/{value}/");

        let mut req = TestRequest::with_uri("/32/").to_srv_request();
        resource.capture_match_info(req.match_info_mut());

        let (req, mut pl) = req.into_parts();
        assert_eq!(
            Path::<i8>::from_request(&req, &mut pl)
                .await
                .unwrap()
                .into_inner(),
            32
        );
        assert!(Path::<MyStruct>::from_request(&req, &mut pl).await.is_err());
    }

    #[actix_web::test]
    async fn test_tuple_extract() {
        let resource = ResourceDef::new("/{key}/{value}/");

        let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
        resource.capture_match_info(req.match_info_mut());

        let (req, mut pl) = req.into_parts();
        let (Path(res),) = <(Path<(String, String)>,)>::from_request(&req, &mut pl)
            .await
            .unwrap();
        assert_eq!(res.0, "name");
        assert_eq!(res.1, "user1");

        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");

        <()>::from_request(&req, &mut pl).await.unwrap();
    }

    #[actix_web::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.capture_match_info(req.match_info_mut());

        let (req, mut pl) = req.into_parts();
        let s = Path::<MyStruct>::from_request(&req, &mut pl).await.unwrap();
        assert_eq!(format!("{s}"), "MyStruct(name, user1)");
        assert_eq!(
            format!("{s:?}"),
            "Path(MyStruct { key: \"name\", value: \"user1\" })"
        );
        let mut s = s.into_inner();
        assert_eq!(s.key, "name");
        assert_eq!(s.value, "user1");
        s.value = "user2".to_string();
        assert_eq!(s.value, "user2");

        let Path(s) = Path::<(String, String)>::from_request(&req, &mut pl)
            .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.capture_match_info(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");
        let s = s.into_inner();
        assert_eq!(s.value, 32);

        let Path(s) = Path::<(String, u8)>::from_request(&req, &mut pl)
            .await
            .unwrap();
        assert_eq!(s.0, "name");
        assert_eq!(s.1, 32);

        let s = Path::<Vec<String>>::from_request(&req, &mut pl)
            .await
            .unwrap();
        let s = s.into_inner();
        assert_eq!(s[0], "name".to_owned());
        assert_eq!(s[1], "32".to_owned());
    }

    #[actix_web::test]
    async fn paths_decoded() {
        let resource = ResourceDef::new("/{key}/{value}");
        let mut req = TestRequest::with_uri("/na%2Bme/us%2Fer%254%32").to_srv_request();
        resource.capture_match_info(req.match_info_mut());

        let (req, mut pl) = req.into_parts();
        let path_items = Path::<MyStruct>::from_request(&req, &mut pl).await.unwrap();
        let path_items = path_items.into_inner();
        assert_eq!(path_items.key, "na+me");
        assert_eq!(path_items.value, "us/er%42");
        assert_eq!(req.match_info().as_str(), "/na%2Bme/us%2Fer%2542");
    }
}