routerify_multipart/
ext.rs

1use crate::{Constraints, Multipart};
2use hyper::{header, Request};
3
4/// An extension trait which extends [`hyper::Request<Body>`](https://docs.rs/hyper/0.14.7/hyper/struct.Request.html)
5/// to add some methods to parse request body as `multipart/form-data`.
6pub trait RequestMultipartExt {
7    /// Convert the request body to [`Multipart`](./struct.Multipart.html) if the `content-type` is `multipart/form-data`.
8    ///
9    /// # Errors
10    ///
11    /// This method fails if the request body is not `multipart/form-data` and in this case, you could send a `400 Bad Request` status.
12    fn into_multipart(self) -> routerify::Result<Multipart<'static>>;
13
14    /// Convert the request body to [`Multipart`](./struct.Multipart.html) if the `content-type` is `multipart/form-data` with some [constraints](./struct.Constraints.html).
15    ///
16    /// # Errors
17    ///
18    /// This method fails if the request body is not `multipart/form-data` and in this case, you could send a `400 Bad Request` status.
19    fn into_multipart_with_constraints(self, constraints: Constraints) -> routerify::Result<Multipart<'static>>;
20}
21
22impl RequestMultipartExt for Request<hyper::Body> {
23    fn into_multipart(self) -> routerify::Result<Multipart<'static>> {
24        let boundary = self
25            .headers()
26            .get(header::CONTENT_TYPE)
27            .and_then(|val| val.to_str().ok())
28            .and_then(|val| multer::parse_boundary(val).ok());
29
30        if let Some(boundary) = boundary {
31            Ok(Multipart::new(self.into_body(), boundary))
32        } else {
33            Err(Box::new(routerify::Error::new(
34                "Content-Type is not multipart/form-data",
35            )))
36        }
37    }
38
39    fn into_multipart_with_constraints(self, constraints: Constraints) -> routerify::Result<Multipart<'static>> {
40        let boundary = self
41            .headers()
42            .get(header::CONTENT_TYPE)
43            .and_then(|val| val.to_str().ok())
44            .and_then(|val| multer::parse_boundary(val).ok());
45
46        if let Some(boundary) = boundary {
47            Ok(Multipart::with_constraints(self.into_body(), boundary, constraints))
48        } else {
49            Err(Box::new(routerify::Error::new(
50                "Content-Type is not multipart/form-data",
51            )))
52        }
53    }
54}